Question

What I want this code to do is handle the exception, and then simply repeat. What it does instead, unfortunately, is loop infinitely... I can't figure out why.

It never asks for the input to be re-entered, seemingly setting it for good the first time. However, this ONLY happens when an exception is thrown; if the user enters an invalid integer, there is no problem at all with the looping process.

I'm relatively new to all this, so I was hoping to get a second opinion before just forcing the loop to exit when an exception is caught.

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");
}
Était-ce utile?

La solution

use finally after catch block and put the following two statements in it like this :

  try {


  } catch(InputMismatchException iox) {


  } finally {

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

 }

Note : When exception occurs before System.out.print("Answer (y/n): "); and answer = scan.next(); statements,these two statements are not executed.But the statements within the finally block executes regardless of what happens within the try block.So,if you use the two statements in finally block these will always be executed infinite looping won't happen.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top