CASE STUDY^461
Responsibility Algorithms:Preparing a file for input and output has become so routine
that we do not need to write the algorithms for these operations. The third responsibil-
ity, processing data, is the heart of the problem. At the topmost level of the design, we
need a loop to process the data from all the sites. Each iteration must process one site’s
data, then check for a new site name. The application does not know in advance how
many recording sites are in the file, so the loop cannot be a count-controlled loop.
Although we can make for,while, or doloops work correctly, we use a doloop under the
assumption that the file definitely contains at least one site’s data. Therefore, we can
set up the loop so that it processes the data from a recording site and then, at the
bottomof the loop, decides whether to iterate again.
Processing one site requires another loop to input 12 monthly rainfall amounts and
sum them. Using the summing technique with which we are highly familiar by now, we
initialize the sum to 0 before starting the loop, and each loop iteration reads another
number and adds it to the accumulating sum. A forloop is appropriate for this task, be-
cause we know that exactly 12 iterations must occur. What if the user has keyed one of
the data values incorrectly? What if a negative value is input? We had better put the for
loop in a try-catchstatement. Once we have the value, we should throw an exception if
it is negative.
Because all of the input values are on one line with a blank in between them, we
must extract the characters that make up one value before we can convert it. We can
Process One Site
Set sum to 0.0
tryto
Get a line of values
formonths going from 1 to 12
Get rainfall amount
ifamount is negative
throwDataSetException("negative value found")
else
Set sum to sum + amount
Write "Average for " + data set name + " is " + sum/12
catchand handle exceptions
Process Data
Prepare input file, inFile
Prepare output file, outFile
Read data set name
do
Process one site
Read data set name
while (more data)
Close files