Scanner类的NoSuchElementException

时间:2017-10-07 21:47:40

标签: java java.util.scanner nosuchelementexception

我的Scanner类有问题,必须从控制台检索一些数据,这里是代码:

private static int getInputFromTheConsole() {
    System.out.println("Enter one of the menu options.");
//    Scanner sc = new Scanner(System.in);
//    return sc.nextInt();
    try(Scanner sc = new Scanner(System.in)) {
        return Integer.parseInt(sc.nextLine());
    } catch (NumberFormatException e) {
        return -1;
    }
}

当我使用两条注释行时,它工作正常,但是当我使用带有try-with-resources的Scanner时,它会抛出NoSuchElementException。 当我尝试在try-catch块中调试程序Scanner时,根本不等待输入,但正如我之前用注释的代码行说的那样它工作正常。 为什么会这样?

1 个答案:

答案 0 :(得分:0)

NoSuchElementException由枚举的nextElement方法抛出,表示枚举中没有更多元素。

因此,您可以通过调用Scanner.hasNextInt()方法检查是否有任何输入。例如

if(sc.hasNextInt() )
     input = sc.nextInt();
相关问题