Java Reference
In-Depth Information
Q
UALITY
T
IP
6.1: Use
for
Loops for Their Intended
Purpose
A
for
loop is an idiom for a
while
loop of a particular form. A counter runs
from the start to the end, with a constant increment:
for (set counter to start; test whether counter at
end;
update counter by increment)
{ . . .
// counter, start, end, increment
not changed here
}
If your loop doesn't match this pattern, don't use the
for
construction. The
compiler won't prevent you from writing idiotic
for
loops:
// Bad style-unrelated header expressions
for (System.out.println(ÐInputs:Ñ);
(x = in.nextDouble()) > 0;
sum = sum + x)
count++;
for (int i = 1; i <= years; i++)
{
// Bad style-modifies counter
if (balance >= targetBalance)
i = years + 1;
else
{
double interest = balance * rate / 100;
balance = balance + interest;
}
}
These loops will work, but they are plainly bad style. Use a
while
loop for
iterations that do not fit the
for
pattern.
241