(^226) | File Objects and Looping Statements
We can solve the problem by reading the first data value beforeentering the loop. This is
called a priming read. (The idea is similar to priming a pump by pouring a bucket of water into
the mechanism before starting it.) Let’s add the priming read to the loop:
// This is still incorrect
date = dataFile.readLine(); // Get a date--priming read
while( !date.equals("0231") )
{
date = dataFile.readLine(); // Get a date
. // Process it
.
.
}
With the priming read, if the first value input is the sentinel value, then the loop correctly
does not process it. We’ve solved one problem, but now a problem crops up when the first
value input is valid data. The first thing the code does inside the loop is to get a date, de-
stroying the value obtained by the priming read. Thus, the first date in the data list is never
processed. Given the priming read, the firstthing that the loop body should do is process the
data that’s already been read. But at what point do we read the next input value? We do so
lastin the loop. In this way, the whilecondition is applied to the next input value before it is
processed. Here’s how it looks:
// This version is correct
date = dataFile.readLine(); // Get a date--priming read
while( !date.equals("0231") )
{
. // Process it
.
.
date = dataFile.readLine(); // Get a date
}
This segment works correctly.The first value is read in; if it is not the sentinel, it is processed.
At the end of the loop, the next value is read in, and we return to the beginning of the loop.
If the new value is not the sentinel, it is processed just like the first value. When the sentinel
value is read, thewhileexpression becomes false, and the loop exits (withoutprocessing the
sentinel).
Many times the problem dictates the value of the sentinel. For example, if the problem
does not allow data values of 0, then the sentinel value should be 0. Sometimes a combina-
tion of values is invalid. The combination of February and 31 as a date is such a case.
Sometimes a range of values (negative numbers, for example) is the sentinel.
When you are choosing a value to use as a sentinel, what happens if no invalid data
values exist? Then you may have to input an extra value in each iteration: a value whose only
purpose is to signal the end of the data. For example, look at this code segment: