【问题标题】:Java do while loop not loopingJava做while循环不循环
【发布时间】:2015-10-04 23:07:17
【问题描述】:

我在执行这个 do while 循环时遇到了一些麻烦。系统将打印出该行并停止。我究竟做错了什么?感谢您的宝贵时间!

Scanner keyboard = new Scanner(System.in);

    String answer;
    int inputNum = 1;
    int countOdd = 0;
    int countEven = 0;

    do{
        do{
            System.out.println("Please enter an interger. When you are finished, enter 0.");
            inputNum = keyboard.nextInt();

                while (inputNum % 2 == 0)
                    countOdd++;
                while (inputNum % 2 != 0)
                    countEven++;
        }while(inputNum != 0);


        System.out.println("Thank you. The amount of odd intergers you entered is " 
        + countOdd + ". The amount of even intergers you entered is " + countEven);


        System.out.println("Thank you. The amount of odd intergers you entered is " 
        + countOdd + ". The amount of even intergers you entered is " + countEven);

        System.out.println("Would you like to run this program again? (Y) (N)");
        answer = keyboard.nextLine();

    }while (answer.equals("Y"));

    System.out.println("Thank you!");
}

}

【问题讨论】:

  • 你关闭过外部{吗?
  • 从来没有听说过 do 循环,只有 do while 循环。时间在哪里?
  • "The system will print out the line and stop" 那么它打印的是什么,您的预期输出是什么?
  • ... 看到@BalwinderSingh 的回答后,我发现nextLine 不是问题所在。 (但在你解决了 while/if 问题之后,这将是你的下一个问题)

标签: java loops do-loops


【解决方案1】:

以下循环无法完成,因为inputNum 内部没有更改:

          while (inputNum % 2 == 0)
                countOdd++;
          while (inputNum % 2 != 0)
                countEven++;

这里需要if 语句而不是while

【讨论】:

    【解决方案2】:

    您需要将while 更改为if。逻辑inputNum%2==0 检查偶数不是奇数。但如果你故意相反,没问题。我改变了它应该是的。

            Scanner keyboard = new Scanner(System.in);
    
        String answer;
        int inputNum = 1;
        int countOdd = 0;
        int countEven = 0;
    
    
            do{
                System.out.println("Please enter an interger. When you are finished, enter 0.");
                inputNum = keyboard.nextInt();
    
                 if (inputNum % 2 == 0)
                     countEven++;
                   if (inputNum % 2 != 0)
                       countOdd++;
            }while(inputNum != 0);
    
    
            System.out.println("Thank you. The amount of odd intergers you entered is " 
            + countOdd + ". The amount of even intergers you entered is " + countEven);
    

    【讨论】:

    • 为什么要投反对票??其 100% 正确答案。加上逻辑也更正了。
    【解决方案3】:

    问题出在以下代码行

    while (inputNum % 2 == 0)
                    countOdd++;
    while (inputNum % 2 != 0)
                    countEven++;
    

    您不会将 while 语句用于 if 条件。而是使用这个

     if (inputNum % 2 == 0)
                        countOdd++;
     if (inputNum % 2 != 0)
                        countEven++;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2020-11-26
      • 2015-02-12
      • 1970-01-01
      • 2016-04-24
      • 2016-06-08
      相关资源
      最近更新 更多