CASE STUDY^249
incomes. Each branch must call the correct update method. After the loop has exited,
we use the knowmethods associated with each gender to output the count and average.
Now we’re ready to write the complete algorithm:
We can use the charAtmethod to extract the gender code from the first position (po-
sition 0) of the input line:
genderCode = inLine.charAt( 0 );
Then we use substringto retrieve the remainder of the line for conversion by
parseDouble:
salary = Double.parseDouble(inLine.substring( 1 , inLine.length()));
All of these algorithms depend on the file being created in a certain way. These
assumptions should be stated in a special section of the design as follows.
Assumptions:There is at least one male and one female among the data sets. The data
sets are entered properly in the input file, with the gender code in the first character
position on each line and a floating-point number starting in the second character po-
sition. The only gender codes in the file are ‘M’ and ‘F’—any other codes are counted as
‘M’. (This last assumption invalidates the results if the data contain any illegal codes.
Case Study Follow-Up Exercise 1 asks you to change the application as necessary to ad-
dress this problem.)
Here is the code for the application.
//
// This application reads a file of income amounts classified by
// gender and computes the average income for each gender.
//
main method
Instantiate inFile
Instantiate outFile
Instantiate female
Instantiate male
whileReading inLine from inFile does not return EOF
Extract gender code and salary from inLine
ifgender code == 'F'
female.update(salary)
else
male.update(salary)
close inFile
Print female.knowCount() and female.knowAverage()
Print male.knowCount() and male.knowAverage()
close outFile