Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


138


// Returns total wages for all employees
public static doubletotalPay()
{
returntotal;
}
}

We now have a simulation of the object on which our application depends, so we can
solve the payroll problem in terms of what the object can do for us. The first task is to
create an object for each employee. In the process, the constructor takes care of
inputting the hours worked, computing the pay, and adding it to the total. Once the ob-
jects are created, all of the work is done, and we just need to report the results. For each
employee object, we print out a message indicating the name and the pay. Finally, we
print the total pay. Here is the algorithm for a payroll with three employees:

Of course, we also need to declare three Employeevariables: emp1,emp2, and emp3. In ad-
dition, we need to wrap all of this in main, inside of a class called Payroll. We need to re-
member to import the Employeeclass. We do not need to import Name, however, because
we don’t use it directly; Employeeimports it for its own use. We still need to import
java.io, even though we don’t directly use the BufferedReaderclass. The reason is that
the Employeeconstructor can throw an IOException, so we need to explicitly throw this
exception to the next level in the heading of main—and the IOExceptionobject is defined
in java.io. If we forget to import java.io, the compiler will complain that IOException
isn’t defined.
We now have three classes in three different files involved in this application: Name,
Employee, and Payroll. How do we get them to find one another? We place the three
class files in the same directory and let Payrollimport Employee, which in turn imports
Name. In Chapter 6, we will show an even better solution: bundling related classes into a
user-defined package.
Now we’re ready to write the application. We’ve added comments where needed.
Here is the code:

//******************************************************************
// Payroll application
// This application computes the pay for three employees
// and also outputs the total pay
//******************************************************************

Payroll Application
Instantiate emp1 (first, last, middle, rate)
Instantiate emp2 (first, last, middle, rate)
Instantiate emp3 (first, last, middle, rate)
Print “Pay “ emp1 name “ $” emp1 pay
Print “Pay “ emp2 name “ $” emp2 pay
Print “Pay “ emp3 name “ $” emp3 pay
Print Employee total pay
Free download pdf