|
| INTERMEDIATE |
A do-while loop is a kind of loop, which is a kind of control statement. It is a loop with the test at the bottom, rather than the more usual test at the top. The syntax is:
do { statements } while (condition);
Here's what it does. First, the statements are
executed, then the condition is tested; if it is
true, then the entire loop is executed again. The loop exits when
the test is performed and gives a false result.
This kind of loop is most often used when the test doesn't make any sense until the statements have been performed at least once. For most purposes, the while loop is preferable.
For example, the user can be asked for a password by:
String input; do { System.out.print("Password? "); input = scanner.nextLine().trim(); } while (!input.equals(PASSWORD));
The braces indicate a block of statements. Unlike other kinds of control statement, the braces in a do-while are required.
In the above example, the variable input was declared before the
loop. Due to scope rules, variables declared within
the block cannot be used within the condition.
Normally, the statements controlled by the loop must affect the condition.
In the above example, the controlled statements change the value of input.
If the controlled statements never make the condition false, then the loop never
exits, and the program "hangs" (stops responding). This is a kind
of error commonly, if inaccurately, called an infinite loop.
Two additional statement types, break
and continue, can also control the
behavior of do-while loops.