2 回答

TA贡献1828条经验 获得超3个赞
因为nextInt()只读取数字,而不是按\n回车后附加的,所以在再次读取数字之前需要清除它,在这个例子中我nextLine()在catch块中做。这里有更深入的解释
工作示例:
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;
}

TA贡献1842条经验 获得超22个赞
一种更简单的方法是在抛出异常之前测试您是否可以读取 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:");
}
}
添加回答
举报