在nextInt()的第二步上修复java.util.InputMismatchException

时间:2019-01-13 23:46:18

标签: java java.util.scanner

我正在编写一个非常简单的程序,在这里我从用户那里得到3个整数,并且想要在将它们存储到单独的变量中进行处理之前进行检查以确保它们都是整数。我使用的检查在第一个输入上有效,但失败了,在第二个输入上抛出异常。

boolean properInt = scanner.hasNextInt();
    int largest = Integer.MAX_VALUE;
    boolean anError = false;


    while(properInt=false){
        anError=true;
        System.out.println("Invalid number...whole numeric values only");
    }

    while(properInt =true){

    int a= scanner.nextInt();
        System.out.println("you entered "+ a);
    int b = scanner.nextInt();
        System.out.println("you entered "+ b);
    int c= scanner.nextInt();
        System.out.println("you entered "+ c);

}

1 个答案:

答案 0 :(得分:0)

原因是当您使用任何nextXxx(...)时,扫描仪光标都将重置为通话之前的位置。输入有效数字后按“输入”键时,扫描仪将忽略“字符”(输入)。但是,当您输入无效值时,将引发异常,并且下一个'nextInt'会将回车键字符视为另一个条件,因此将不起作用。

我建议先使用nextLine,然后使用Integer.ParseInt并捕获NumberFormatException

此外,您的while循环检查不正确。

properInt=false is a statement.

while(properInt==false) is a condition..

英语不是我的强项,所以如果它令人困惑,请告诉我。

相关问题