Java Reference
In-Depth Information
while (years < 20)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Here the programmer forgot to add a statement for incrementing years in the
loop. As a result, the value of years always stays 0 , and the loop never comes to
an end.
232
233
Another common reason for an infinite loop is accidentally incrementing a counter
that should be decremented (or vice versa). Consider this example:
int years = 20;
while (years > 0)
{
years++; // Oops, should have been years--
double interest = balance * rate / 100;
balance = balance + interest;
}
The years variable really should have been decremented, not incremented. This
is a common error, because incrementing counters is so much more common than
decrementing that your fingers may type the ++ on autopilot. As a consequence,
years is always larger than 0 , and the loop never terminates. (Actually, years
eventually will exceed the largest representable positive integer and wrap around
to a negative number. Then the loop exitsȌof course, that takes a long time, and
the result is completely wrong.)
C OMMON E RROR 6.2: Off-by-One Errors
Consider our computation of the number of years that are required to double an
investment:
int years = 0;
while (balance < 2 * initialBalance)
{
years++;
double interest = balance * rate / 100;
balance = balance + interest;
}
System.out.println(
Search WWH ::




Custom Search