我需要解释为什么输出是a-b c-d

时间:2020-04-18 09:03:34

标签: java

public class Main {
    public static void main(String[] args) {
        int x = 3;  
        while(x > 0) {      
            if(x > 2) {
                System.out.print("a"); 
            }

            x = x - 1;
            System.out.print("-");

            if(x == 2) {
                System.out.print("b c");
            }

            if(x == 1) {
                System.out.print("d");
                x = x - 1;
            }           
        }
    }
}

输出:a-b c-d

在打印“ b c”时,x的值应该为2,为什么还要打印“ d”?

3 个答案:

答案 0 :(得分:3)

仔细查看代码段

    int x = 3;  
    while(x > 0) {      
        if(x > 2) {
            System.out.print("a"); 
        }

        x = x - 1;
        System.out.print("-");

        if(x == 2) {
            System.out.print("b c");
        }

        if(x == 1) {
            System.out.print("d");
            x = x - 1;
        }           
    }

第一次运行循环时,x的值为3,并且发生以下操作

    while(x > 0) {      
        if(x > 2) {
            System.out.print("a"); // as the value is 3 so it ll print
        }

        x = x - 1; // here value is 2 now
        System.out.print("-"); // it ll be printed all the time the loop runs

        if(x == 2) {
            System.out.print("b c"); // again this ll be printed because the value is 2
        }

        if(x == 1) {
            System.out.print("d");
            x = x - 1;
        }           
    }

现在x的值为2,并且发生以下操作

    while(x > 0) {   // value of x is 2   
        if(x > 2) {
            System.out.print("a"); // it is skipped as the value of x is 2
        }

        x = x - 1; // now the value of x is 1
        System.out.print("-"); // it gets printed again

        if(x == 2) {
            System.out.print("b c"); // it gets skipped as the value is 1
        }

        if(x == 1) {
            System.out.print("d"); // it gets printed 
            x = x - 1; // loop gets over here as the value becomes 0
        }           
    }

我已经简化了它,以便您理解:)

答案 1 :(得分:0)

因为循环一直运行到X == 0,这意味着它将循环运行一次并打印a,bc,然后它会检查X == 0(不是),x = x-1,现在x == 1以及打印d。循环再次运行,使x == 0,然后停止

First round - X == 3, so it prints "a",
X = X - 1, Now x == 2
X== 2, so it prints "bc"
jumps over the last if statement since x > 1.

Second round
X is not 3 so it doesnt print.
X = X -1, now x == 1,
X is not 2, so now print, 
X== 1 so it prints d.

third round since X > 0
only thing happening is X = X -1;
now X == 0, and the while loop will end 

答案 2 :(得分:0)

最好是像调试器一样浏览代码。一行一行。

您看到您的程序包裹在 while循环中,while(x>0)意味着只要x大于0,整个代码块都会重复。

第一次迭代

在正确打印出“ b c”后,您就在第一次迭代中,x的值为2。程序将跳过打印“ d”。至此,while循环的第一个迭代结束了。

第二次迭代时

现在检查while的条件x为2,这意味着(x> 0),程序将进入while循环的第二次迭代。 “ a”将不会打印。 x减小到1。将不打印“ b-c”。 x为1时,“ d”将被打印到控制台。

第三次迭代

条件检查x的值。 x = 1,它的值大于零,因此在执行循环时再次出现。这次x减少到0。什么都不打印,因为if语句都不满足。

结束

由于x为0,它不再大于0,因此不满足while循环的条件。 While循环将不会执行,程序将结束。

检查并播放while循环

Oracle docs

W3schools