Java Reference
In-Depth Information
PITFALL: (continued)
This for loop is indeed iterated 10 times, but since the body is the empty statement,
nothing happens when the body is iterated. This loop does nothing, and it does noth-
ing 10 times! After completing this for loop, the computer goes on to execute the fol-
lowing, which writes Hello to the screen one time:
System.out.println("Hello");
This same sort of problem can arise with a while loop. Be careful to not place a
semicolon after the closing parenthesis that encloses the Boolean expression at the start
of a while loop. A do-while loop has just the opposite problem. You must remember
to always end a do-while loop with a semicolon.
PITFALL: Infinite Loops
A while loop, do-while loop, or for loop does not terminate as long as the controlling
Boolean expression evaluates to true . This Boolean expression normally contains a
variable that will be changed by the loop body, and usually the value of this variable
eventually is changed in a way that makes the Boolean expression false and therefore
terminates the loop. However, if you make a mistake and write your program so that
the Boolean expression is always true, then the loop will run forever. A loop that runs
forever is called an infinite loop .
Unfortunately, examples of infinite loops are not hard to come by. First, let's
describe a loop that does terminate. The following Java code writes out the positive
even numbers less than 12. That is, it outputs the numbers 2, 4, 6, 8, and 10, one per
line, and then the loop ends.
infinite loop
number = 2;
while (number != 12)
{
System.out.println(number);
number = number + 2;
}
The value of number is increased by 2 on each loop iteration until it reaches 12. At that
point, the Boolean expression after the word while is no longer true, so the loop ends.
Now suppose you want to write out the odd numbers less than 12, rather than the
even numbers. You might mistakenly think that all you need to do is change the ini-
tializing statement to
number = 1;
But this mistake will create an infinite loop. Because the value of number goes from 11
to 13, the value of number is never equal to 12, so the loop never terminates.
Search WWH ::




Custom Search