Java.util.scanner错误处理 [英] Java.util.scanner error handling
本文介绍了Java.util.scanner错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在帮助一个Java问题的朋友.但是,我们遇到了障碍.我们正在使用Java.Util.Scanner.nextInt()从用户那里获取一个数字,不断询问用户是否还提供了其他任何东西.唯一的问题是,我们无法弄清楚如何进行错误处理.
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.
我们尝试过的事情:
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.
有帮助吗?
推荐答案
您可以使用nextLine().
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".
所以,像这样:
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 + ")");
另请参见:
查看全文