java do while循环如何与try catch转到无穷大?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (94)

以下是我使用的代码:

do {
        try {
                System.out.println("Please enter the type of employee. (1 - salaried, 2 - hourly, 3 - commissioned)");
                type = user_input.nextInt();
                letter = true;
            }
            catch (InputMismatchException e) {
                letter = false;
                System.out.print("Entered value is not an integer. Try again.");
            }
        } while (!letter);
提问于
用户回答回答于

解决方案:

String type = null;
Scanner user_input = new Scanner(System.in);
boolean letter = true;
do {
    try {
        System.out.println("Please enter the type of employee. (1 - salaried, 2 - hourly, 3 - commissioned)");
        type = user_input.nextLine();
        Integer.valueOf(type);
    } catch (Throwable e) {
        letter = false;
        System.out.print("Entered value is not an integer. Try again.");
    }
} while (letter);

扫码关注云+社区

领取腾讯云代金券