(^230) | File Objects and Looping Statements
until it comes to a zero. (Both numberand countare of type int.) The loop in the following ex-
ample has a counter variable, but it is not a count-controlled loop because the variable is not
used as a loop control variable:
count = 0; // Initialize counter
number = Integer.parseInt(inFile.readLine()); // Read a number
while(number != 0) // Test the number
{
count++; // Increment counter
number = Integer.parseInt(inFile.readLine()); // Read a number
}
The loop continues until a zero is read. After the loop is finished,countcontains one less than
the number of values read. That is, it counts the number of values up to, but not including,
the sentinel value (the zero). If a zero is the first value, the loop body is not entered and count
contains a zero, as it should. We use a priming read here because the loop is sentinel-con-
trolled, and because it is easier to understand the intent of the loop test than if we write it
using our shortcut. Here’s how the loop looks if we use an assignment in the comparison:
count = 0; // Initialize counter
while((number = Integer.parseInt(inFile.readLine())) != 0)
count++; // Increment counter
As you can see, this code is shorter, but its meaning is not nearly as obvious
to the reader. A good Java compiler generates Bytecode that is equally efficient in
both cases, so it is better to use the version that is easier to understand.
The counter variable in this example is called an iteration counterbecause its
value equals the number of iterations through the loop. According to our defini-
tion, the loop control variable of a count-controlled loop is an iteration counter.
However, as you’ve just seen, not all iteration counters are loop control variables.
What happens if our example loop encounters EOF before it reads a zero? It crashes
with a NumberFormatException. The reason is that readLinereturns nullwhen the file pointer
is at EOF. The parseIntmethod cannot convert this value to a number, so it throws an ex-
ception. The loop is thus more properly written as follows:
count = 0; // Initialize counter
inLine = inFile.readLine(); // Read a number string
if (inLine == null) // If EOF
number = 0; // Set number to 0
else
{
number = Integer.parseInt(inFile.readLine()); // Convert string to int
while(number != 0) // Test the number
{
count++; // Increment counter
inLine = inFile.readLine(); // Read a number string
Iteration counter A counter
variable that is incremented in
each iteration of a loop
T
E
A
M
F
L
Y
Team-Fly®
やまだぃちぅ
(やまだぃちぅ)
#1