Java Reference
In-Depth Information
242
C OMMON E RROR 6.3: Forgetting a Semicolon
Occasionally all the work of a loop is already done in the loop header. Suppose
you ignored Quality Tip 6.1; then you could write an investment doubling loop as
follows:
for (years = 1;
(balance = balance + balance * rate / 100)
< targetBalance;
years++)
;
System.out.println(years);
The body of the for loop is completely empty, containing just one empty statement
terminated by a semicolon.
If you do run into a loop without a body, it is important that you make sure the
semicolon is not forgotten. If the semicolon is accidentally omitted, then the next
line becomes part of the loop statement!
for (years = 1;
(balance = balance + balance * rate / 100)
< targetBalance;
years++)
System.out.println(years);
You can avoid this error by using an empty block { } instead of an empty
statement.
C OMMON E RROR 6.4: A Semicolon Too Many
What does the following loop print?
sum = 0;
for (i = 1; i <= 10; i++);
sum = sum + i;
System.out.println(sum);
Of course, this loop is supposed to compute 1 + 2 + ș + 10 = 55. But actually, the
print statement prints 11!
Search WWH ::




Custom Search