Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^135


SMALL COMPANY PAYROLL


Problem:You’re running a small company with just a few part-time employees, and you
want an application that computes their week’s pay.


Input:The hours worked for each employee, entered as real numbers via System.in.


Output:The pay for each employee, and the company’s total pay for the week.


Discussion:This calculation would be easy to do by hand, but it is a good exercise for ex-
ploring the use of numerical input and object-oriented problem solving.
The objects in our problem are employees, so we would like to define a class for an
employee. An employee in this case has a name, a pay rate, a number of hours worked,
and wages earned. These items can be instance fields in our class. For each employee,
we need to input the hours worked and compute the pay. This task can be a
responsibility of the constructor.
Once we have an employee object, we need to get the name of the employee, the
amount of pay for the employee, and the total pay for all employees. The name and pay
for the employee are associated with each instance of an employee, while the total pay
is a property of the entire class of employees. Thus we need instance methods to return
the employee’s name and pay, and a class method to return the total pay, which should
be kept in a class field. Let’s look at each of these methods in turn.
The constructor must get the employee name and pay rate, which can be passed in
as arguments and stored in the instance fields. Because the employees change
infrequently, we can encode these arguments as literal constants in the constructor
calls. The hours worked are different each time we run the application, so we need to
input them. The constructor must prompt the user via System.outand read the
response via System.in. As we’ve seen, data is input as a string, which we must convert
to a doublevalue using the parseDoublemethod.
Once we have the hours, computing the pay is quite easy: We simply multiply the
pay rate times the hours worked. The only tricky part is rounding the result to the near-
est cent. Without this step, we are likely to get results that include fractions of cents. In
this chapter, we showed how to round a floating-point value to the nearest integer by
adding 0.5 and using a type cast to truncate the result:


(int)((double)Value + 0.5))


To round to the nearest cent, we first multiply the value by 100, round the result to the
nearest integer, and then divide by 100 again. For example, ifdoubleValuecontains
5.162, then


(double)((int)(doubleValue * 100.0+ 0.5)) / 100.0

Free download pdf