Programming and Problem Solving with Java

(やまだぃちぅ) #1
5.2 Looping | 227

data = dataFile.readLine(); // Get first data line
sentinel = data.substring(0, 1); // Extract sentinel character
while(sentinel.equals("Y"))
{
// Extract data value from line and convert to double
value = Double.parseDouble(data.substring(1, data.length()));


. // Process data value
.
.
data = dataFile.readLine(); // Get next data line
sentinel = data.substring(0, 1); // Extract sentinel character
}


The first value on each line of the following data set is used to indicate whether more data are
present. In this data set, when the sentinel value is anything other than Y, no more data remain;
when it is Y, more data should be processed.


Sentinel Data
Values Values
Y 12.78
Y –47.90
Y 5.33
Y 21.83
Y –99.01
N
What happens if you forget to include the sentinel value? Once all the data have been
read from the file, the loop body is executed again. However, there aren’t any data left—be-
cause the computer has reached the end of the file. In the next section, we describe a way
to use the end-of-file situation as an alternative to a sentinel.


End-of-File-Controlled Loops After an application has read the last piece of data from an input file,


the computer is at the end of the file (EOF, for short). The next time that we attempt to read
from the file, there is nothing to read and thus nothing for the readLinemethod to return. What
happens? The readLinemethod normally returns a Stringvalue that holds the contents of
the line, so it returns nullas its sentinel.
Thus, to read and process lines from a file, we can write a sentinel-controlled loop like
the following:


line = dataFile.readLine(); // Get a line--priming read
while( line != null)
{


. // Process it
.
.
line = dataFile.readLine(); // Get the next line
}

Free download pdf