你可以使用的诸多一个hasNext*
是方法Scanner
有预验证。
if (in.hasNextInt()) {
int a = in.nextInt() ;
System.out.println(a);
} else {
System.out.println("Sorry, Couldn't understand you!");
}
这可以防止InputMismatchException
从甚至被抛出,因为你总是确保它WILL你读它之前匹配。
boolean hasNextInt()
:返回true
是否可以使用nextInt()
方法将此扫描器输入中的下一个标记解释为默认基数中的int值。扫描仪不会越过任何输入。
String nextLine()
:使此扫描仪前进到当前行,并返回跳过的输入。
请记住以粗体显示的部分。hasNextInt()
不会超过任何输入。如果返回true
,你可以通过调用来推进扫描程序nextInt()
,不会抛出异常InputMismatchException
。
如果返回false
,则需要跳过“垃圾”。最简单的方法是调用nextLine()
,可能两次,但至少一次。
为什么你可能需要做nextLine()
两次以下操作:假设这是输入的内容:
42[enter]
too many![enter]
0[enter]
假设扫描仪位于该输入的开头。
Scanner in = new Scanner (system.in) ;
System.out.println("Age?");
while (!in.hasNextInt()) {
in.next(); // What happens if you use nextLine() instead?
}
int age = in.nextInt();
in.nextLine(); // What happens if you remove this statement?
System.out.println("Name?");
String name = in.nextLine();
System.out.format("[%s] is %d years old", name, age);
假设输入为:
He is probably close to 100 Now...[enter]
Elvis, of course[enter]
然后输出的最后一行是:
[Elvis, of course] is 100 years old