do {
try {
System.out.print("Please enter the hour:");
hour = consoleScanner.nextInt();
if (hour < 1 || hour > 12) {
throw new InvalidHourException();
}
System.out.print("Please enter the minute:");
minute = consoleScanner.nextInt();
if (minute < 0 || minute > 59) {
throw new InvalidMinuteException();
}
if (minute <= 9)
zero = "0";
System.out.print("Please enter either \"AM\" or \"PM\":");
meridiem = consoleScanner.next();
if (!(meridiem.equalsIgnoreCase("AM"))
&& !(meridiem.equalsIgnoreCase("PM"))) {
throw new InvalidMeridiemException();
}
} catch (InvalidHourException hourEx) {
System.out.println(hourEx.getMessage());
consoleScanner.nextLine();
errorOccured = true;
} catch (InvalidMinuteException minuteEx) {
System.out.println(minuteEx.getMessage());
consoleScanner.nextLine();
errorOccured = true;
} catch (InvalidMeridiemException meriEx) {
System.out.println(meriEx.getMessage());
consoleScanner.nextLine();
errorOccured = true;
}
} while (errorOccured);
System.out.println(hour + ":" + zero + minute + meridiem + " is a valid time.");
consoleScanner.close();
}
}
这是我的while while循环。 输出是:
Please enter the hour:8
Please enter the minute:60
Please enter a minute between 1 to 60
Please enter the hour:
为什么它会跳回到小时而不是分钟? catch语句中有什么问题吗?
答案 0 :(得分:1)
由于您只有一个try块,并且只要抛出任何异常就重复它,在捕获异常后,即使问题不是小时输入,也会执行提示小时的代码。 / p>
为了不重复请求已经有效的输入,你需要为3个输入中的每一个输入一个单独的while循环+ try-catch块。
除此之外,当输入有效时,您应将errorOccured
设置为false。否则你永远不会离开循环。