简体   繁体   English

不符合条件的嵌套while循环

[英]nested while-loop that doesn't match the condition

I am trying to make a program that print the following numbers : 我正在尝试制作一个打印以下数字的程序:

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4

The code is 该代码是

   public class JavaApplication8 {

    public static void main(String[] args) {

        int i = 1;
        int j = 1;

        while (i <= 2 && j <= 4) {

            while (i <= 2 && j <= 4) {

                System.out.printf("%d%d\n", i, j);

                j++;
            }

            j = j - 4;

            i++;

            System.out.printf("%d%d\n", i, j);
            j++;

        }

    }
}

The program prints this 程序打印此

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1

I don't know why this is happening behind the condition inside while says that it i must be smaller or equal 2 我不知道为什么这种情况发生在内部条件背后,而我说它必须小于或等于2

It's outputting that final 3 1 because your final println statement (indicated below) is unconditional. 由于最后的println语句(如下所示)是无条件的,因此将输出最后的3 1 So after incrementing i to 3, you still run that statement. 因此,将i增至3后,您仍然可以运行该语句。 The while condition only takes effect afterward, which is why it then stops after printing that. while条件仅在之后生效,这就是为什么它在打印完之后就停止的原因。

public class JavaApplication8 {

    public static void main(String[] args) {

        int i = 1;
        int j = 1;

        while (i <= 2 && j <= 4) {

            while (i <= 2 && j <= 4) {

                System.out.printf("%d%d\n", i, j);

                j++;
            }

            j = j - 4;

            i++;

            System.out.printf("%d%d\n", i, j); // <=== This one
            j++;

        }

    }
}

That whole thing can be dramatically simpler, though: 不过,整个过程可以大大简化:

public class JavaApplication8 {
    public static void main(String[] args) {
        for (int i = 1; i <= 2; ++i) {
            for (int j = 1; j <= 4; ++j) {
                System.out.printf("%d%d\n", i, j);
            }
        }
    }
}

Live Example 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM