Java Reference
In-Depth Information
Here, the integer
i
is given the value of
10
. When the
while
loop is first encountered, the condi-
tional expression
i
> 0
is evaluated: 10 is greater than 0, so the expression is
true
. The program
outputs
"10"
to the console, then returns to the start of the
while
loop again. The conditional
expression
i
> 0
is evaluated again, but
i
is still equal to 10 and 10 is greater than 0 so the expres-
sion is still
true
. Again, you'll see an output of
"10"
to the console. This will continue indefinitely,
creating an infinite loop. To prevent this, you can add a statement inside the
while
loop to alter the
value of the variable
i
.
int i = 10;
while (i > 0){
System.out.println(i);
i = i - 1;
}
This time, the conditional expression
10 > 0
is still
true
when the
while
loop is first encountered.
During the first iteration, the output
"10"
will be printed to the console, then
int
i
will be reas-
signed the value
i
-1
or 9. The conditional expression will be evaluated again to
true
, so the loop
will be repeated. Now
9
will be output to the console and
int
i
will be reassigned the value 8. This
will continue until
i
= 0
, when the expression will evaluate to
false
.
It's possible that your conditional expression is not a variable at all. You will see some classic
examples of
while
loops in Chapter 7 when dealing with inputs and outputs. For now, it's enough
to understand that the
Scanner
class has two methods,
hasNextLine()
and
nextLine()
, that can
be used when scanning files, to determine if a file still has more lines to be scanned, and to actually
scan the next line, respectively.
int lines = 0;
while (myScanner.hasNextLine()){
lines++;
}
This code might look like it will count the number of lines in the file being scanned by
myScan-
ner
. However, this will actually create an infinite loop like the first
while
loop you saw. That's
because the program never moves past the first line of the file. When the loop is first encoun-
tered, assuming the file has at least one line in it, the conditional expression
hasNextLine()
will
evaluate to
true
. The variable lines will be reassigned the value
0+1
or
1
and the conditional
expression will remain
true
. In order to ensure that the loop will end and the correct number
of lines will be counted, you have to progress through the lines of the file using the
nextLine()
method.
int lines = 0;
while (myScanner.hasNextLine()){
myScanner.nextLine(); //scan the next line
lines++;
}
In this way, in each iteration of the
while
loop, the scanner will scan another line of the file until the
end of the file is reached. Then, the conditional expression
hasNextLine()
will evaluate to
false
and the program will not enter the loop again.
Search WWH ::
Custom Search