Payroll-Arrays01: An Array of employees - Exercise

Contact Us or call 1-877-932-8228
Payroll-Arrays01: An Array of employees - Exercise

Payroll-Arrays01: An Array of employees

Duration: 20 to 30 minutes.
  1. Modify the payroll program to use an array of Employee objects with a size of 3 or more (later we will come up with a more flexible solution that allows for the number of employees to change dynamically).
  2. Use a for loop to populate and display the data.
  3. After the loop is complete, ask the user to enter a last name.
  4. Loop through the array to find the element with the matching last name and display it.

Solution:

Solutions/Payroll-Arrays01/Payroll.java
import employees.*;
import util.*;

public class Payroll {	
	public static void main(String[] args) {
		Employee[] e = new Employee[5];
		String fName = null;
		String lName = null;
		int dept = 0;
		double payRate = 0.0;

		for (int i = 0; i < e.length; i++) {
			fName = KeyboardReader.getPromptedString("Enter first name: ");
			lName = KeyboardReader.getPromptedString("Enter last name: ");
			do {
				dept = KeyboardReader.getPromptedInt("Enter department: ");
				if (dept <= 0) System.out.println("Department must be >= 0");
			} while (dept <= 0);
			do {
				payRate = KeyboardReader.getPromptedDouble("Enter pay rate: ");
				if (payRate < 0.0) System.out.println("Salary must be >= 0");
			} while (payRate < 0.0);
			e[i] = new Employee(fName, lName, dept, payRate);
			System.out.println(e[i].getPayInfo());
		}

		lName = KeyboardReader.getPromptedString("Enter last name to find: ");
		boolean notFound = true;
		for (int i = 0; i < e.length; i++) {
			if (lName.equalsIgnoreCase(e[i].getLastName())) {
				System.out.println("Found: " + e[i].getPayInfo());
				notFound = false;
				break;
			}
		}
		if (notFound) System.out.println("Not found");
	}
}

The code uses e[i].getPayInfo() to print the pay information for employee i. Element i of the array is one employee reference. It uses the same approach to call e[i].getLastName() for each employee to compare with the requested name.

Next