Java Reference
In-Depth Information
232
S YNTAX 6.1 The while Statement
while (condition)
statement
Example:
while (balance < targetBalance)
{
years++;
double interest = balance * rate / 100;
balance = balance + interest;
}
Purpose:
To repeatedly execute a statement as long as a condition is true
S ELF C HECK
1. How often is the following statement in the loop executed?
while (false) statement;
2. What would happen if RATE was set to 0 in the main method of the
InvestmentRunner program?
C OMMON E RROR 6.1: Infinite Loops
The most annoying loop error is an infinite loop: a loop that runs forever and can
be stopped only by killing the program or restarting the computer. If there are
output statements in the loop, then reams and reams of output flash by on the
screen. Otherwise, the program just sits there and hangs, seeming to do nothing.
On some systems you can kill a hanging program by hitting Ctrl+Break or Ctrl+C.
On others, you can close the window in which the program runs.
A common reason for infinite loops is forgetting to advance the variable that
controls the loop:
int years = 0;
Search WWH ::




Custom Search