Java.util.scanner 错误处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2696063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java.util.scanner error handling
提问by Hussain
I'm helping a friend with a java problem. However, we've hit a snag. We're using Java.Util.Scanner.nextInt() to get a number from the user, asking continiously if the user gives anything else. Only problem is, we can't figure out how to do the error handeling.
我正在帮助一个有 Java 问题的朋友。然而,我们遇到了障碍。我们正在使用 Java.Util.Scanner.nextInt() 从用户那里获取一个数字,不断询问用户是否提供了其他信息。唯一的问题是,我们无法弄清楚如何进行错误处理。
What we've tried:
我们尝试过的:
do {
int reloop = 0;
try {
number = nextInt();
} catch (Exception e) {
System.out.println ("Please enter a number!");
reloop ++;
}
} while(reloop != 0);
Only problem is, this loops indefinatly if you enter in something not a number.
唯一的问题是,如果您输入的不是数字,则会无限循环。
Any help?
有什么帮助吗?
采纳答案by polygenelubricants
You can use hasNextInt()
to verify that the Scanner
will succeed if you do a nextInt()
. You can also call and discard nextLine()
if you want to skip the "garbage".
您可以使用hasNextInt()
验证Scanner
,如果你做一个会成功nextInt()
。nextLine()
如果你想跳过“垃圾”,你也可以调用并丢弃。
So, something like this:
所以,像这样:
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("int, please!");
sc.nextLine();
}
int num = sc.nextInt();
System.out.println("Thank you! (" + num + ")");
See also:
也可以看看:
The problem with your code, in addition to the unnecessarily verbose error handling because you let nextInt()
throw an InputMismatchException
instead of checking for hasNextInt()
, is that when it doesthrow an exception, you don't advance the Scanner
past the problematic input! That's why you get an infinite loop!
您的代码的问题,除了因为您让nextInt()
throw anInputMismatchException
而不是检查 for 而不必要的冗长错误处理之外hasNextInt()
,当它确实抛出异常时,您不会Scanner
将有问题的输入提前!这就是为什么你会得到一个无限循环!
You can call and discard the nextLine()
to fix this, but even better is if you use the exception-free hasNextInt()
pre-check technique presented above instead.
您可以调用并丢弃nextLine()
来解决此问题,但更好的是如果您使用hasNextInt()
上面介绍的无异常预检查技术。
回答by Nick Z.
if the number is non-int , exception will pop, if not reloop will become 1 , and loop will exit
如果数字是非 int ,则异常将弹出,如果不是,则 reloop 将变为 1 ,并且循环将退出
int reloop = 0;
do {
try {
number = nextInt();
reloop ++;
} catch (Exception e) {
System.out.println ("Please enter a number!");
}}
while(reloop == 0);