如何检查Scanner输入是否为整数,如果是,则从循环中断

时间:2017-05-29 01:00:09

标签: java while-loop int

首先,如果我要复制一个帖子,我很抱歉。我试着寻找解决方案但找不到它。我正在制作一个成绩计算器,用户输入一个双倍的" x"通过扫描仪的次数。我已经掌握了它的基本原理,并且我没有尝试修复用户在输入数字时可能遇到的任何问题。

public static void main(String args[]) {

    double total = 0;
    int counter = 0;

    ArrayList<String> answerYes = new ArrayList<>();
    answerYes.add("yes");
    answerYes.add("y");
    answerYes.add("yea");


    Scanner answerCheck = new Scanner(System.in);
    System.out.println("Would you like to submit a number to calculate the average? [y/n]");
    String userInput = answerCheck.nextLine();
    while (answerYes.contains(userInput)) {
        Scanner numberInput = new Scanner(System.in);
        System.out.println("Please input a number: ");
        Integer number = numberInput.nextInt(); //Here is where I need to check for a non-integer.
        total += number;
        System.out.println("Would you like to submit another number to calculate the average? [y/n]");
        userInput = answerCheck.nextLine();
        counter++;
    }
    double average = total/counter;
    System.out.println("The average of those numbers is: " + average);

}

我很确定我比这更复杂,但是我想测试一下平均计算器的能力,就像没有互联网一样。希望我能正确格式化。

谢谢, 约旦

2 个答案:

答案 0 :(得分:1)

我认为你要做的就是这样。

try {
    int input = scanner.nextInt();
    // remaining logic
} catch (InputMismatchException e) {
    System.out.println("uh oh");
}

因此,如果用户输入的内容无法作为整数读取,则会抛出InputMismatchException

您可以通过将其置于循环中来强制用户在继续之前输入数字来扩展它。

答案 1 :(得分:1)

您只需要一个Scanner,并且可以使用String.startsWith而不是检查集合。像,

double total = 0;
int counter = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to submit a number to calculate the average? [y/n]");
String userInput = scan.nextLine();
while (userInput.toLowerCase().startsWith("y")) {
    System.out.println("Please input a number: ");
    if (scan.hasNextInt()) {
        total += scan.nextInt();
        counter++;
    }
    scan.nextLine();
    System.out.println("Would you like to submit another number to calculate the average? [y/n]");
    userInput = scan.nextLine();
}
double average = total / counter;
System.out.println("The average of those numbers is: " + average);