Scanner类的nextInt()方法在while循环中不要求我再次输入



在我的主要方法中是这样的代码:

int hours = getHours();

这是get hours((代码:

public static int getHours() {
int hours = 0;
boolean hoursNotOk = true;
do {
try {
hours = console.nextInt();
hoursNotOk = false;
}catch(Exception e) {
System.out.print(e);

}finally {
if(hoursNotOk) {
System.out.print(", please re-enter the hours again:");
}else {
System.out.print("**hours input accepted**");
}
}
}while(hoursNotOk);

return hours;
}

console.nextInt((第一次要求我输入,所以假设我在控制台中输入了一个"二",它会抛出一个异常并再次循环通过try块,但这次它没有要求我输入并一直从catch打印出来,最后阻止,为什么会发生这种情况?

因为nextInt()只读取数字,而不是在您点击return后附加的n,所以在您可以再次读取数字之前,您需要清除它,在本例中,我在catch块中执行nextLine()。这里有更深入的解释

工作示例:

public static int getHours() {
int hours = 0;
boolean hoursNotOk = true;
do {
try {
System.out.println("Here");
hours = console.nextInt();
hoursNotOk = false;
} catch (Exception e) {
e.printStackTrace();
console.nextLine();
} finally {
if (hoursNotOk) {
System.out.println(", please re-enter the hours again:");
} else {
System.out.println("**hours input accepted**");
}
}
} while (hoursNotOk);
return hours;
}

一种更简单的方法是在抛出异常之前测试是否可以读取int。在任何情况下,您都需要在重试之前放弃当前单词或行。

public static int getHours() {
while (true) {
if (console.hasNextInt()) {
System.out.print("**hours input accepted**");
return console.nextInt();
}
console.nextLine(); // discard the line and try again
System.out.print(", please re-enter the hours again:");
}
}

最新更新