Payroll-Control01: Modified Payroll - Exercise

Contact Us or call 1-877-932-8228
Payroll-Control01: Modified Payroll - Exercise

Payroll-Control01: Modified Payroll

Duration: 10 to 15 minutes.

We will modify our payroll program to check the pay rate and department values.

  1. The Employee class should protect itself from bad data, so modify setPayRate and setDept to check the incoming data (and ignore it if it is less than 0).
  2. Test your program to see what happens with negative input values.
  3. The code using Employee should avoiding sending it bad data, so also change main in to check for acceptable pay rate and department values (print an error message for any negative entry, then just set that variable to 0 (for lack of anything better that we can do right now. Later we will find a way to ask the user for a new value instead)


package employees;

public class Employee {

---- C O D E   O M I T T E D ----
	public int getDept() { return dept; }

	public void setDept(int dept) {
		if (dept > 0) this.dept = dept;

	public double getPayRate() { return payRate; }

	public void setPayRate(double payRate) {
		if (payRate >= 0) this.payRate = payRate;

---- C O D E   O M I T T E D ----

The Employee class should protect itself from bad incoming data, so the setPayRate method simply ignores a value less than 0. A better practice, which we will add later, would be to throw an exception when an illegal value is passed in. Note the benefit of coding the constructors to use the setPayRate method; we do not have to go back and revise their code as well. (setDept has similar changes.)


import employees.*;
import util.*;

public class Payroll {	
	public static void main(String[] args) {
		Employee e1 = null, e2 = null, e3 = null;
		String fName = null;
		String lName = null;
		int dept = 0;
		double payRate = 0.0;

		fName = KeyboardReader.getPromptedString("Enter first name: ");
		lName = KeyboardReader.getPromptedString("Enter last name: ");
		dept = KeyboardReader.getPromptedInt("Enter department: ");
		if (dept <= 0) { 
			System.out.println("Department must be > 0");
			dept = 0;
		payRate = KeyboardReader.getPromptedDouble("Enter payRate: ");
		if (payRate < 0.0) {
			System.out.println("Pay rate must be >= 0");
			payRate = 0.0;
		e1 = new Employee(fName, lName, dept, payRate);

---- C O D E   O M I T T E D ----

Even though Employee now protects itself from illegal incoming values, it should really be the responsibility of the progmmers for the classes using Employee to avoid sending it bad values. So, the payRate value is tested here as well. While this may seem to decrease efficiency (since, presumably, a non-object-oriented program might be able to avoid testing the value twice in a row), the maintainability aspects of OOP are still considered to outweigh the loss in efficiency.