Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^232) | File Objects and Looping Statements
adds the current value of sum(0) to numberto form the new value of sum. After the entire code
fragment has executed,sumcontains the total of the 10 values read,countcontains 11, and
numbercontains the last value read.
In the preceding code,countis incremented in each iteration. For each new value of
count, there is a new value for number. Does this mean we could decrement countby 1 and in-
spect the previous value of number? No. Once a new value has been read into number, the pre-
vious value is gone forever unless we’ve saved it in another variable (or we reset the file and
reread the data).
Let’s look at another example. This time, let’s also check for EOF. We want to count and
sum the first 10 odd numbers in a data set. To do so, we need to test each number to see
whether it is even or odd. (We can use the modulus operator to find out. If number % 2
equals 1,numberis odd; otherwise, it’s even.) If the input value is even, we do nothing. If it
is odd, we increment the counter and add the value to our sum. We use a flag(a boolean
variable) to control the loop because this is not a normal count-controlled loop. In the
following code segment, all variables are of type intexcept the String lineand the boolean
flag,notDone.
count = 0; // Initialize event counter
sum = 0; // Initialize sum
notDone = true; // Initialize loop control flag
while(notDone)
{
line = dataFile.readLine(); // Get a line
if (line != null) // Got a line?
{
number = Integer.parseInt(line); // Convert line to an int
if (number % 2 == 1) // Is the int value odd?
{
count++; // Yes--increment counter
sum = sum + number; // Add value to sum
notDone = (count < 10); // Update loop control flag
}
}
else // Hit EOF unexpectedly
{
errorFile.println("EOF reached before ten odd values read.");
notDone = false; // Update loop control flag
}
}
We control the loop with the flag notDone, because the loop exits when either of two
events occurs: reading and processing 10 odd values or reaching EOF. Because we use a
Boolean flag to control the loop, this type of loop is often called a flag-controlled loop.
In this example, there is no relationship between the value of the counter variable and
the number of times that the loop is executed. Note that countis incremented only when an

Free download pdf