开发者

question about loop and break command

i have tested following code which might print 0 and 2 but it print 1 and 1 why?

public class break_command {


    public static void main(String[] args) {
       for (int i=0;i<10;i++){
            for (int j=1;j<10;i++){
                if ((i+j) %2==0){
                    System.out.println("i  "+ i +"  j   " +j);
                开发者_JAVA百科    break;
                }


            }
            break;
       }
    }

}

result//
i  1  j   1
BUILD SUCCESSFUL (total time: 0 seconds)


Is the line:

for (int j=1;j<10;i++){

Supposed to be j++ not i++?

Otherwise it means on the first iteration:

if ((i+j) %2==0){

Will be true.


You are iterating i inside your second loop, not j. So initially, in the first loop, i has the value 0. Then as you enter the second loop, it is increased to 1. At this point i has the value 1 and j has the value one; their sum is even, so it prints them out and breaks out of the inner loop, breaks out of the outer loop, and you are done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜