Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


248


// Returns average of salary values added with update
public doubleknowAverage()
{
returntotalSalary / (double)count;
}
}

Now we can turn to the processing for this application and its mainmethod; let’s call
this class Incomes. We need to prepare the files for input and output, then process the
data on the input file. After the last value has been input, we write the output to its file.
Of course, we also need to close the files when we’re finished with them.
We must write the file processing as a loop that involves two subtasks, because we
must process two genders instead of just one. We use our checklist of questions to de-
velop these subtasks in detail.
1.What condition ends the loop?The termination condition is EOF on the file inFile.It
leads to the following loop test (in pseudocode):

2.How should the condition be initialized?A priming read must take place to enter a
gender code and amount.
3.How should the condition be updated?We must input a new data line with a gender
code and amount at the end of each iteration.
We must input each data line as a string. Then we need to extract the gender
code and amount from the string. Because the input of the line is a single opera-
tion, we can combine the priming read and the updating read using Java’s
assignment expression shortcut. Here’s the resulting algorithm:

4.What is the process being repeated?We need to update the appropriate Gender
object with the input data.
5.How should the process be initialized?femaleand maleobjects need to be
instantiated.
6.How should the process be updated?When a female income is input,female.update
is called. Otherwise, an income is assumed to be for a male, so male.updateis
called.
7.What is the state of the code on exiting the loop?The file inFileis at EOF; femalecon-
tains the number of input values preceded by ‘F’ and their total salary; malecon-
tains the number of values not preceded by ‘F’ and the sum of those values.
From the description of how the process is updated, we can see that the loop must
contain an ifstructure, with one branch for female incomes and one branch for male

whileReading inLine from inFile does not return EOF
Extract gender code and amount from inLine
 (Process being repeated)

whileNOT EOF on inFile
Free download pdf