[英]Java do while loop not looping
I'm having a bit of trouble with this do while loop. 我在做这个while循环时有点麻烦。 The system will print out the line and stop. 系统将打印出该行并停止。 What am I doing wrong? 我究竟做错了什么? Thank you for your time! 感谢您的时间!
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!");
}
} }
The following loops cannot be finished, since inputNum
is not changed inside: 由于inputNum
在内部未更改,因此以下循环无法完成:
while (inputNum % 2 == 0)
countOdd++;
while (inputNum % 2 != 0)
countEven++;
You need if
statements here instead of while
. 您需要if
语句而不是while
语句。
You need to change while
with if
. 你需要改变while
与if
。 The logic inputNum%2==0
checks for even not odd.But if you did it intentionally opposite ,its fine. 逻辑inputNum%2==0
检查偶数是否为奇数。但是,如果您有意相反,则可以。 I changed it as it should be. 我按原样更改了它。
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);
The problem is with the following lines of code 问题在于以下几行代码
while (inputNum % 2 == 0)
countOdd++;
while (inputNum % 2 != 0)
countEven++;
You don't use while
statements for if
conditions. 您不对if
条件使用while
语句。 Instead use this 改用这个
if (inputNum % 2 == 0)
countOdd++;
if (inputNum % 2 != 0)
countEven++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.