java - 如果扫描仪接收到 int 以外的内容,则会创建无限循环
问题描述
在这个 java 方法中,重点是让扫描仪接收最小值和最大值之间的 int。如果接收到超出这些范围的int ,则程序会正确输出“无效输入”。但是,如果输入诸如“g”或“h”之类的内容或 int 以外的内容,则会创建一个无限循环。
我试图在代码中的多个位置重新初始化扫描仪,但看起来当从 System.in 输入除 int 以外的其他内容时,它只是再次通过扫描仪飞行并保持循环继续进行。有什么想法吗
public static int promptInt(int min, int max) {
while (false != true) {
int b = 0;
Scanner scnr = new Scanner(System.in);
System.out.print("Choose a value between " + min + " and " + max + ": ");
if (scnr.hasNext()) {
if (scnr.hasNextInt()) {
b = scnr.nextInt();
if (b <= max) {
return b;
} else {
System.out.println("Invalid Value");
}
}
else if (scnr.hasNextInt() == false) {
System.out.println("Not an Int");
}
}
}
}
解决方案
根据上面的一些评论,需要 scnr.next() 否则它会继续检查已初始化的第一个扫描仪。这是现在起作用的修改后的代码。
public static int promptInt(int min, int max) {
Scanner scnr = new Scanner(System.in);
while (false != true) {
int b = 0;
System.out.print("Choose a number between " + min + " and " + max + ": ");
if (scnr.hasNext()) {
if (scnr.hasNextInt() == false) {
System.out.println("Invalid value.");
//the scnr.next was needed here
scnr.next();
}
else {
b = scnr.nextInt();
if (b <= max) {
return b;
} else {
System.out.println("Invalid value.");
}
}
}
}
}
推荐阅读
- android - Android:如何在来自 Firestore 的小部件中显示数据?
- time-complexity - 2个嵌套循环的时间复杂度
- python-3.x - 在引发前面的异常时捕获由“finally”引起的异常
- database - 是否有可以操作布尔值的数据库
- java - 测试时没有匹配的bean,但在服务器上完美运行
- php - Getting Column not found Error at Illuminate\Database\QueryException?
- docker - docker run 中的卷和 dockerfile 中的 COPY 的差异
- javascript - 有没有办法通过 Pixi.js 画一个环?
- rust - rust 中的“match ref”是什么意思?
- laravel - Laravel 安排推送通知并在必要时取消它