Java.util.scanner 错误处理
我正在帮助一个朋友解决java问题。然而,我们遇到了障碍。我们使用 Java.Util.Scanner.nextInt() 从用户那里获取一个号码,不断询问用户是否提供了其他信息。唯一的问题是,我们不知道如何进行错误处理。
我们尝试过的:
do {
int reloop = 0;
try {
number = nextInt();
} catch (Exception e) {
System.out.println ("Please enter a number!");
reloop ++;
}
} while(reloop != 0);
唯一的问题是,如果您输入的不是数字,则会无限循环。
有什么帮助吗?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
hasNextInt()
来验证如果您执行nextInt()
,Scanner
将会成功。如果您想跳过“垃圾”,您还可以调用并丢弃nextLine()
。所以,像这样:
另请参阅:
除了不必要的冗长错误处理之外,您的代码存在问题,因为您让
nextInt()
抛出InputMismatchException
而不是检查hasNextInt()
,就是当它确实抛出异常时,您不会将扫描器
推进到有问题的输入之前!这就是为什么你会得到无限循环!您可以调用并丢弃
nextLine()
来解决此问题,但如果您使用上面介绍的无异常hasNextInt()
预检查技术,效果会更好。You can use
hasNextInt()
to verify that theScanner
will succeed if you do anextInt()
. You can also call and discardnextLine()
if you want to skip the "garbage".So, something like this:
See also:
The problem with your code, in addition to the unnecessarily verbose error handling because you let
nextInt()
throw anInputMismatchException
instead of checking forhasNextInt()
, is that when it does throw an exception, you don't advance theScanner
past the problematic input! That's why you get an infinite loop!You can call and discard the
nextLine()
to fix this, but even better is if you use the exception-freehasNextInt()
pre-check technique presented above instead.如果数字是非 int ,则会弹出异常,如果不是则重新循环将变为 1 ,并且循环将退出
if the number is non-int , exception will pop, if not reloop will become 1 , and loop will exit