Java Reference
In-Depth Information
Condition—keep looping while this
condition is still true
while ( degCent != 100)
{
// some code
}
Code looped through
Figure 3-12
You can see that the while loop has fewer parts to it than the for loop. The while loop consists of a con-
dition 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.
One thing to watch out for is that if the condition is false to start with, the while loop never executes.
For example:
degCent = 100;
while (degCent != 100)
{
// some code
}
Here, the loop will run if degCent does not equal 100. However, since 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:
degCent = new Array();
degFahren = new Array(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 fi rst line after the closing brace of the while statement.
Search WWH ::




Custom Search