Loop和if语句不提供所需的输出

时间:2016-09-04 04:00:43

标签: java

public class Shuffle1 {
    public static void main(String[] args) {
        int x = 3;

        if(x > 2) {
            System.out.print("a");
        }

        while(x > 0) {
            x = x - 1;
            System.out.print("-");
        }

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

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

我正在从一本名为“Head First Java”的书中学习Java,我正在使用本书中推荐的TextEdit。我应该能够编译代码来获得a-b c-d的答案,但是每次我编译它时,我得到的结果是---。我亲自检查过,如果有人能帮助我,我会非常感激。 Here is the original question from the book.

2 个答案:

答案 0 :(得分:1)

因此,如果x为3,我将带您了解所发生的事情:

  1. 打印" a"因为3> 2
  2. x减少为0,打印" - "在途中,因为它需要2个减量来满足中断条件,x> 0
  3. 这意味着它会正确打印a--。要实现a-b c-d,必须在循环中使用if语句,如下所示:

    while(x > 0) {
        x = x - 1;
        System.out.print("-");
    
        if(x == 2) {
            System.out.print("b c");
        }
    
        if(x == 1) {
            System.out.print("d");
            x = x - 1;
        }
    }
    

    现在执行周期为:

    1. x> 2,所以打印" a"
    2. 进入循环
    3. x变为2
    4. 打印" - "
    5. x是2,所以打印" b c"
    6. 继续迭代
    7. 下一次迭代,x变为1
    8. 打印" - "
    9. x为1,因此打印" d"
    10. x现在为0
    11. 终止循环
    12. 这会得到以下所需结果:a-b c-d

答案 1 :(得分:1)

这将根据您的期望打印。

public class Shuffle1 {
    public static void main(String[] args) {
        int x = 3;    

        if(x > 2) {   //First time x=3, which is true
            System.out.print("a");  // print a
        }

        while(x > 0) {  // x=3, which is true
            x = x - 1;   //first loop, x=2, then second loop x=1
            System.out.print("-");  //prints "-"

          if(x == 2) {  // x=2, which is true
            System.out.print("b c"); //prints "b c"
             }

        if(x == 1) {  // as x=2, so it won't get display in first loop, but when it loop for second time, x become 1, which is true. 
            System.out.print("d");
            x = x - 1;
           }
        }
    }
}