你可以使用的诸多一个
hasNext*是方法
Scanner有预验证。
if (in.hasNextInt()) { int a = in.nextInt() ; System.out.println(a); } else { System.out.println("Sorry, couldn't understand you!"); }
这可以防止
InputMismatchException从甚至被抛出,因为你总是确保它WILL你读它之前匹配。
java.util.Scanner API
boolean hasNextInt()
:返回true
是否可以使用nextInt()
方法将此扫描器输入中的下一个标记解释为默认基数中的int值。扫描仪不会越过任何输入。String nextLine()
:使此扫描仪前进到当前行,并返回跳过的输入。
请记住以粗体显示的部分。
hasNextInt()不会超过任何输入。如果返回
true,你可以通过调用来推进扫描程序
nextInt(),不会抛出异常
InputMismatchException。
如果返回
false,则需要跳过“垃圾”。最简单的方法是调用
nextLine(),可能两次,但至少一次。
为什么你可能需要做
nextLine()两次以下 *** 作:假设这是输入的内容:
42[enter]too many![enter]0[enter]
假设扫描仪位于该输入的开头。
hasNextInt()
是真实的,nextInt()
回报42;扫描仪现在位于第一个扫描仪之前[enter]
。hasNextInt()
为假,nextLine()
返回一个空字符串,一秒钟nextLine()
返回"too many!"
;扫描仪现在是刚过第二[enter]
。hasNextInt()
是真实的,nextInt()
回报0;扫描仪现在在之前第三[enter]
。
这是将其中一些内容放在一起的示例。你可以尝试使用它来研究其Scanner
工作原理。
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)