我无法使该程序正常运行。输入数字后,没有任何反应。有人可以指出我要去哪里了吗?

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

最佳答案

请考虑使用nextLine()代替nextInt(),以获得更好的错误处理方案。

因为nextInt()将尝试读取传入的输入。它将看到此输入不是整数,并且肯定会引发异常。但是,输入不会清除,它仍然存在。缓冲区中仍然有"abcxyz"。因此,回到循环将导致它尝试反复分析相同的"abcxyz"

使用nextLine()将至少清除缓冲区,以便在输入错误行之后输入的新输入将是错误后读取的下一个输入。

09-13 06:47