java.util.Scanner已经可以使用方法检查下一个标记是否具有给定的模式/类型
hasNextXXX。
这是一个
boolean hasNext(Stringpattern)使用正则表达式用于验证下一个标记仅由字母组成的示例
[A-Za-z]+:
Scanner sc = new Scanner(System.in); System.out.println("Please enter letters:"); while (!sc.hasNext("[A-Za-z]+")) { System.out.println("Nope, that's not it!"); sc.next(); } String word = sc.next(); System.out.println("Thank you! Got " + word);这是一个示例会话:
Please enter letters:&#@#$Nope, that's not it!123Nope, that's not it!james bondThank you! Got james
要验证下一个令牌是可以转换为的数字,请
int使用
hasNextInt(),然后使用
nextInt()。



