我无法让这个程序正常运行。输入数字后没有任何反应。有人可以指出我出错的地方吗?
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
//Declare variables
int number;
int evenNumbers = 0;
int oddNumbers = 0;
String answer = " ";
//Create Scanner
Scanner input = new Scanner(System.in);
do {
//Prompt the user to enter a list of positive numbers with the last being a negative
System.out.println("Please enter a list of positive numbers separated by a space.");
System.out.println("(Enter a negative number after all positive numbers have been entered.)");
//Read the users numbers
number = input.nextInt();
//An if statement determing a number either even or odd
while (number >= 0) {
if (number % 2 == 0) {
evenNumbers++;
} else {
oddNumbers++;
}//end of else
//Read next number
number = input.nextInt();
}//end of while
//Display total number of even and odd integers
System.out.println("The total number of even positive intergers is: " + evenNumbers);
System.out.println("The total number of odd positive integers is: " + oddNumbers);
//Ask the us if they would like to play again
System.out.println("Would you like to play again? Please type: 'yes' or 'no': ");
//Move scanner to next line
input.nextLine();
//Read the users input
answer = input.nextLine();
} while(answer.equalsIgnoreCase("yes") ); //end of do-while
}//end of main
}//end of class
答案 0 :(得分:2)
请考虑使用nextLine()
代替nextInt()
以获得更好的错误处理方案。
因为nextInt()会尝试读取传入的输入。它将看到此输入不是整数,并且肯定会抛出异常。但是,输入没有被清除,它仍然存在。缓冲区中仍然会有"abcxyz"
。因此,回到循环将导致它尝试一遍又一遍地解析相同的"abcxyz"
。
使用nextLine()
将至少清除缓冲区,以便您在错误之后读取的下一个输入将是您输入的坏行之后的新输入。
答案 1 :(得分:0)
我认为在这种情况下,你的期望是错误的。该程序告诉您输入由空格后跟负数分隔的正数。我猜你可能没有输入负数,这就是循环的原因:
while (number >= 0)
继续执行,等待一个负整数值,触发它停止并继续前进。
您可能想要解决的一些小问题: