Java Reference
In-Depth Information
Common Programming Error
Infinite Loop
It is relatively easy to write a
while
loop that never terminates. One reason it's
so easy to make this mistake is that a
while
loop doesn't have an update step
in its header like a
for
loop does. It's crucial for the programmer to include a
correct update step because this step is needed to eventually cause the loop's
test to fail.
Consider the following code, which is intended to prompt the user for a num-
ber and repeatedly print that number divided in half until 0 is reached. This first
attempt doesn't compile:
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
// this code does not compile
while (number > 0) {
int number = console.nextInt();
System.out.println(number / 2);
}
The problem with the preceding code is that the variable
number
needs to be in
scope during the loop's test, so it cannot be declared inside the loop. An incorrect
attempt to fix this compiler error would be to cut and paste the line initializing
number
outside the loop:
// this code has an infinite loop
int number = console.nextInt(); // moved out of loop
while (number > 0) {
System.out.println(number / 2);
}
This version of the code has an infinite loop; if the loop is entered, it will
never be exited. This problem arises because there is no update inside the
while
loop's body to change the value of
number
. If
number
is greater than
0
, the loop
will keep printing its value and checking the loop test, and the test will evaluate
to
true
every time.
Continued on next page
Search WWH ::
Custom Search