异常处理引起的无限循环

时间:2014-04-20 05:19:21

标签: java input exception-handling while-loop infinite-loop

我希望这段代码能够处理异常,然后重复一遍。不幸的是,它的作用是无限循环......我无法弄清楚原因。

它永远不会要求重新输入输入,似乎第一次将其设置为好。但是,这只会在抛出异常时发生;如果用户输入了无效的整数,则循环过程完全没有问题。

我对这一切都比较新,所以我希望在抓住异常时强制循环退出之前得到第二个意见。

Scanner scan = new Scanner(System.in);

// Variables associated with the clock:
private int h; // h = Hours
private int m; // m = Minutes
private int s; // s = Seconds

public boolean userPrompt() {

    String answer = "";

    // Loops while until a clock is generated and selected
    while (! answer.equals("y")) {

        System.out.println("What time is it?");

        try {

            // Asking for the time, one variable at a time.
            System.out.print("H >> ");
            h = scan.nextInt();

            System.out.print("M >> ");
            m = scan.nextInt();

            System.out.print("S >> ");
            s = scan.nextInt();

            // Testing for the validity of the clock's time:
            if ((h < 24 && h >= 0) && (m < 60 && m >= 0) && (s < 60 && s >= 0)) {

                // Displaying the formatted clock's time:
                System.out.printf("Clock { %02d:%02d:%02d }\n", h, m, s);

                System.out.println("Save clock generated?");

                System.out.print("Answer (y/n): ");
                answer = scan.next();
            }
        } catch (InputMismatchException iox) {

            // Here lies the issue, I think...
            System.out.println("ERROR: " +iox);
        }
    }

    // A safeguard for the next method in the program
    return answer.equals("y");
}

1 个答案:

答案 0 :(得分:1)

finally阻止之后使用catch并将以下两个语句放在其中:

  try {


  } catch(InputMismatchException iox) {


  } finally {

   System.out.print("Answer (y/n): ");
            answer = scan.next();

 }

注意:在System.out.print("Answer (y/n): ");之前发生异常时                 answer = scan.next();语句,这两个语句不会被执行。但是finally块中的语句不管try块中发生了什么,都会执行。所以,如果你在{{{{}}中使用这两个语句1}}阻止这些将永远执行无限循环不会发生。