2015-10-04 82 views
1

我在执行循环操作时遇到了一些麻烦。系统将打印出行并停止。我究竟做错了什么?感谢您的时间!Java在循环不循环时执行操作

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!"); 
} 

}

+0

你有没有关闭外面的'''? – brandaemon

+1

从来没有听说过做循环,只有一个while while循环。什么时候? – mmking

+0

@brandaemon yes –

回答

4

下面的循环是无法完成的,因为inputNum不改变里面:

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

你在这里,而不是while需要if声明。

1

问题是与代码

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

以下行不要使用while报表if条件。相反,使用此

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

您需要更改whileif。逻辑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); 
+1

为什么选择下调?它的100%正确答案。此外,逻辑也被纠正。 –