Java Reference
In-Depth Information
balance <= 2 * initialBalance , the loop would have executed once
more.
In other words, you keep adding interest while the balance has not yet doubled.
A DVANCED T OPIC 6.1: do Loops
Sometimes you want to execute the body of a loop at least once and perform the
loop test after the body was executed. The do loop serves that purpose:
do
statement
while (condition);
The statement is executed while the condition is true. The condition is tested after
the statement is executed, so the statement is executed at least once.
For example, suppose you want to make sure that a user enters a positive number.
As long as the user enters a negative number or zero, just keep prompting for a
correct input. In this situation, a do loop makes sense, because you need to get a
user input before you can test it.
double value;
do
{
System.out.print(ÐPlease enter a positive
number: Ñ);
value = in.nextDouble();
}
while (value <= 0);
The figure shows a flowchart of this loop.
Search WWH ::




Custom Search