do while syntax for java

别说谁变了你拦得住时间么 提交于 2019-12-24 00:25:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!