Java 循环和if语句没有给出所需的输出

Java 循环和if语句没有给出所需的输出,java,Java,我正在从一本名为“头先Java”的书中学习Java,并按照书中的建议使用TextEdit。我应该能够编译代码以得到a-b c-d的答案,但是每次编译它时,我都会得到一个--。我自己已经彻底检查过了,如果有人能帮助我,我将不胜感激。 因此,如果x为3,我将告诉您发生了什么: 打印出“a”,因为3>2 递减x到0,正在打印“-”,因为需要两次递减才能满足中断条件,x>0 这意味着它将正确打印a--。要实现a-b c-d,必须在循环中使用if语句,如下所示: public class Shuffle1

我正在从一本名为“头先Java”的书中学习Java,并按照书中的建议使用TextEdit。我应该能够编译代码以得到a-b c-d的答案,但是每次编译它时,我都会得到一个--。我自己已经彻底检查过了,如果有人能帮助我,我将不胜感激。

因此,如果
x
为3,我将告诉您发生了什么:

  • 打印出“a”,因为3>2
  • 递减
    x
    到0,正在打印“-”,因为需要两次递减才能满足中断条件,x>0
  • 这意味着它将正确打印
    a--
    。要实现
    a-b c-d
    ,必须在循环中使用if语句,如下所示:

    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;
            }
        }
    }
    
    现在执行周期是:

  • x
    >2,所以打印“a”
  • 进入循环
  • x
    变为2
  • 印刷品“-”
  • x
    是2,所以打印“bc”
  • 继续迭代
  • 下一次迭代,
    x
    变为1
  • 打印“-”
  • x
    为1,所以打印“d”
  • x
    现在为0
  • 终止循环

  • 这将提供以下所需结果:
    a-b c-d

    这将按照您的期望进行打印

    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;
        }
    }
    

    我认为第二个和第三个
    if
    语句应该在
    while
    循环中。在调试器中单步执行代码可以真正帮助调试程序。它还将帮助你通过练习逐步完成头脑中的代码。请稍等,我正在写。。
    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;
               }
            }
        }
    }