问题描述
所以,我被这段代码困住了:
So, I'm getting stuck with this piece of code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsoleReader {
Scanner reader;
public ConsoleReader() {
reader = new Scanner(System.in);
//reader.useDelimiter(System.getProperty("line.separator"));
}
public int readInt(String msg) {
int num = 0;
boolean loop = true;
while (loop) {
try {
System.out.println(msg);
num = reader.nextInt();
loop = false;
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
}
}
return num;
}
}
这是我的输出:
插入一个整数:
无效值!
插入一个整数:
无效值!
...
推荐答案
根据 javadoc 用于扫描仪:
当扫描仪抛出一个InputMismatchException,扫描器不会传递导致的令牌例外,所以它可能是通过其他一些检索或跳过方法.
这意味着如果下一个标记不是 int
,它会抛出 InputMismatchException
,但标记会留在那里.所以在循环的下一次迭代中,reader.nextInt()
再次读取相同的标记并再次抛出异常.你需要的是用完它.在你的 catch
中添加一个 reader.next()
来消费令牌,令牌无效,需要丢弃.
That means that if the next token is not an int
, it throws the InputMismatchException
, but the token stays there. So on the next iteration of the loop, reader.nextInt()
reads the same token again and throws the exception again. What you need is to use it up. Add a reader.next()
inside your catch
to consume the token, which is invalid and needs to be discarded.
...
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
reader.next(); // this consumes the invalid token
}
这篇关于如何使用 Scanner 处理由无效输入(InputMismatchException)引起的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!