简体   繁体   English

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

[英]Why does my code keep repeating itself after an exception comes up?

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();

}
}

this is my do while loop. 这是我的do while循环。 The output is: 输出为:

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

why does it jump back to the hour instead of the minutes? 为什么跳回到小时而不是分钟? Is there something wrong in the catch statements? catch语句中有什么问题吗?

Since you have a single try block, and you repeat it whenever any exception is thrown, after an exception is caught, the code that prompts for the hour is executed, even if the problem wasn't with the hour input. 由于您只有一个try块,并且每当引发任何异常时都重复该块,因此在捕获到异常之后,将执行提示输入小时的代码,即使问题并非与输入小时相关。

In order not to repeat requesting for inputs that were already valid, you'll need a separate while loop + try-catch block for each of the 3 inputs. 为了不重复请求已经有效的输入,您需要为3个输入中的每个输入单独的while循环+ try-catch块。

Beside that, you should set errorOccured to false when the input is valid. 除此之外,当输入有效时,应将errorOccured设置为false。 Otherwise you'll never leave the loop. 否则,您将永远不会离开循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM