Java Reference
In-Depth Information
Let's take a look at the structure of the
while
statement, as
illustrated in Figure 3-12.
Condition—keep looping while this
condition is still true
You can see that the
while
loop has fewer parts to it
than the
for
loop. The
while
loop consists of a condition
which, if it evaluates to
true
, causes the block of code
inside the curly braces to execute once; then the condition
is re‐evaluated. If it's still
true
, the code is executed again,
the condition is re‐evaluated, and so on until the condition
evaluates to
false
.
while ( degCent != 100)
{
// some code
}
One thing to watch out for is that if the condition is
false
to
start with, the
while
loop never executes. For example:
Code looped through
var degCent = 100;
figure 3-12
while (degCent != 100) {
// some code
}
Here, the loop will run if
degCent
does not equal
100
. However, because
degCent
is
100
, the
condition is
false
, and the code never executes.
In practice you would normally expect the loop to execute once; whether it executes again will
depend on what the code inside the loop has done to variables involved in the loop condition. For
example:
var degCent = [];
degFahren = [34, 123, 212];
var loopCounter = 0;
while (loopCounter < 3) {
degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32);
loopCounter++;
}
The loop will execute so long as
loopCounter
is less than
3
. It's the code inside the loop
(
loopCounter++;
) that increments
loopCounter
and will eventually cause
loopCounter < 3
to be
false
so that the loop stops. Execution will then continue on the first line after the closing brace of
the
while
statement.
Something to watch out for is the
infinite loop
—a loop that will never end. Suppose you forgot to
include the
loopCounter++;
line in the code. Leaving this line out would mean that
loopCounter
will remain at
0
, so the condition
(loopCounter < 3)
will always be
true
, and the loop will
continue until the user gets bored and cross, and shuts down her browser. However, it is an easy
mistake to make, and one that JavaScript won't warn you about.
It's not just missing lines that can cause infinite loops, but also mistakes inside the loop's code. For
example:
var testVariable = 0;
while (testVariable <= 10) {