java - 如何修复 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;
}
如果有人知道如何解决此问题,我将不胜感激。
解决方案
推荐阅读
- javascript - 交互式地图,如何在 symfony 中创建从地图标记弹出到模板的链接
- android - Room Proguard - 重新混淆旧的数据库成员
- javascript - NodeJS - 从 Google Drive 下载媒体
- mysql - MariaDB 和 MySQL 中比较日期的差异
- wordpress - 在 docker 中使用 wpcli 导出数据库
- excel - 使用箭头键将光标置于 ActiveX 文本框中
- javascript - 尝试使用 javascript addEventListener 更新 css 变量,但它只工作一次
- r - 使用条件将一列中的整个值替换为另一列
- r - 如何按位置替换字符串的一部分
- sql - 如何替换SQL中所有出现的字符串