首页 > 解决方案 > 如何修复 NoSuchElementException

问题描述

我设置了一个方法来检查输入是否与 int 类型匹配,并且在匹配之前不会返回。

到目前为止,它在几个项目中运行良好,但是当我在当前的项目中使用它时,我在第二次进入该方法时遇到了这种错误。

Exception in thread "main" java.util.NoSuchElementException

这是方法:

private static int inputHandler() {
    Scanner sc = new Scanner(System.in);
    int num = 0;

    try{
        System.out.println("Enter a number:");
        num = sc.nextInt();
    } catch(InputMismatchException e){
        System.out.println("Input must match type int");
        num = inputHandler();
    }
    sc.close();
    return num;
} 

如果有人知道如何解决此问题,我将不胜感激。

标签: javainputtry-catchjava.util.scannernosuchelementexception

解决方案


推荐阅读