gpt4 book ai didi

java - 如何使用 Scanner 处理无效输入(InputMismatchException)引起的无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:53 25 4
gpt4 key购买 nike

所以,我被这段代码困住了:

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;
}
}

这是我的输出:

Insert a integer number:
Invalid value!
Insert a integer number:
Invalid value!
...

最佳答案

根据javadoc对于扫描仪:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

这意味着如果下一个标记不是 int,它会抛出 InputMismatchException,但标记仍保留在那里。因此,在循环的下一次迭代中,reader.nextInt() 再次读取相同的标记并再次引发异常。你需要的是用完它。在 catch 中添加一个 reader.next() 来消耗 token ,该 token 无效,需要丢弃。

...
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
reader.next(); // this consumes the invalid token
}

关于java - 如何使用 Scanner 处理无效输入(InputMismatchException)引起的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56876279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com