问题
Ages since I have written a do while.
Whats wrong with this do while
int i = 0;
do {
System.out.println(i);
} while(++i == 500);
I only goes once through the loop, and IMO it should iterate 500 times.
回答1:
You probably meant
while (++i < 500);
instead of
while (++i == 500);
回答2:
It is a do-while
loop of Java, not the repeat-until
loop of Pascal. Its expression specifies the continuation condition, not the exit condition.
do {
System.out.println(i);
} while(++i != 500);
回答3:
It will only iterate once because of your condition. while (++i == 500)
++i
will be 1 and never 500, so it evaluates to false and won't continue.
回答4:
In your code initially the value of i (i.e. 0) will be printed because it is a do while and the code inside the loop should be executed at least once.
And then now the condition will be checked. It will be checked that if ++i equals 500 (i.e 1==500) which returns false and hence the loop breaks.
while (++i < 500);
changing the condition to the above statement may cause the loop to continue untill the value of i becomes 500
回答5:
while(++i != 500)
{
System.out.println(i);
}
is the better way.
来源:https://stackoverflow.com/questions/10834202/do-while-syntax-for-java