我正在编写命令行程序,并希望让用户输入有效的年龄(整数)。通过使用扫描仪类,我有这样的事情:检查用户是否输入整数
int getAge() {
Scanner = new Scanner(System.in);
int age;
boolean isValid = false;
while(!isValid) {
System.out.println("Please enter your age");
if (myScanner.hasNext()) {
if (myScanner.hasNextInt()) {
age = myScanner.nextInt();
isValid = true;
} else {
System.out.println("Please enter an integer");
}
}
}
return age;
}
的问题是,虽然在循环它不断读取输入,而不必等待新的价值。我怎样才能解决这个问题?