Java 为什么我的代码在出现异常后不断重复?

Java 为什么我的代码在出现异常后不断重复?,java,Java,为什么它跳回到小时而不是分钟?catch语句中是否有错误?因为您只有一个try块,并且每当抛出任何异常时都会重复该块,因此在捕获异常后,将执行提示输入小时的代码,即使该问题与小时输入无关 为了不重复请求已经有效的输入,您需要为3个输入中的每一个单独的while循环+try catch块 除此之外,当输入有效时,应将erroroccurrend设置为false。否则,您将永远不会离开循环。“为什么它跳回到小时而不是分钟?”您指的是跳到小时异常处理位吗?也许是步骤调试?嘿@QuakeCore,我想知

为什么它跳回到小时而不是分钟?catch语句中是否有错误?

因为您只有一个try块,并且每当抛出任何异常时都会重复该块,因此在捕获异常后,将执行提示输入小时的代码,即使该问题与小时输入无关

为了不重复请求已经有效的输入,您需要为3个输入中的每一个单独的while循环+try catch块


除此之外,当输入有效时,应将
erroroccurrend
设置为false。否则,您将永远不会离开循环。

“为什么它跳回到小时而不是分钟?”您指的是跳到小时异常处理位吗?也许是步骤调试?嘿@QuakeCore,我想知道为什么;必须移除吗?当它被删除时,它会给我一个语法错误。谢谢@elequang我的错它不应该被移除非常感谢你@Eran,你真是救命恩人!我理解出了什么问题,发生了什么。
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();

}
}
Please enter the hour:8
Please enter the minute:60
Please enter a minute between 1 to 60
Please enter the hour: