Java Reference
In-Depth Information
int tmp = j;
j = j + 1;
j = tmp;
The program repeats this process 100 times, after which the value of
j
is exactly what it was before
the loop, or 0.
Fixing the program is as simple as removing the extraneous assignment from the loop, leaving:
for (int i = 0; i < 100; i++)
j++;
With this modification, the program prints
100
as expected.
The lesson is this the same as in
Puzzle 7
:
Do not assign to the same variable more than once in a
single expression.
An expression containing multiple assignments to the same variable is confusing
and seldom does what you want.
< Day Day Up >
Search WWH ::
Custom Search