0

In my main method is this code:

int hours = getHours();

Here is the get hours() code:

public static int getHours() {

    int hours = 0;
    boolean hoursNotOk = true;

    do {
    try {
        hours = console.nextInt();
        hoursNotOk = false;

    }catch(Exception e) {
        System.out.print(e);



    }finally {
        if(hoursNotOk) {
            System.out.print(", please re-enter the hours again:");

        }else {
            System.out.print("**hours input accepted**");
        }
    }
    }while(hoursNotOk);


    return hours;
}

For the first time console.nextInt() ask me for input, so lets say I put in a "two" in the console, it will throw an exception and loop through the try block again but this time it did not ask me for input and keeps printing out from the catch and finally block, why is this happening?

Nigel Ng
  • 133
  • 8
  • Well, that's because you are not asking for input anywhere but the `finally` block. – Guy Nov 11 '18 at 12:19

2 Answers2

2

Because nextInt() only reads the number, and not the \n appended after you hit return, you need to clear that before you can read a number again, in this example I do nextLine() in the catch block. here's more indepth explanation

Working example:

public static int getHours() {
    int hours = 0;
    boolean hoursNotOk = true;

    do {
        try {
            System.out.println("Here");
            hours = console.nextInt();
            hoursNotOk = false;

        } catch (Exception e) {
            e.printStackTrace();
            console.nextLine();
        } finally {
            if (hoursNotOk) {
                System.out.println(", please re-enter the hours again:");

            } else {
                System.out.println("**hours input accepted**");

            }
        }
    } while (hoursNotOk);

    return hours;
}
Mark
  • 4,515
  • 2
  • 17
  • 29
  • If I just put this in the main method while(true) { someVar = console.nextInt();} why would it not need console.nextLine()? – Nigel Ng Nov 11 '18 at 12:59
  • @NigelNg If I try that it either works when I enter a number or throws an exception when I enter a character. – Mark Nov 11 '18 at 15:34
1

A simpler approach is to test whether you can read an int before throwing an exception. In any case, you need to discard the current word or line before trying again.

public static int getHours() {
    while (true) {
        if (console.hasNextInt()) {
            System.out.print("**hours input accepted**");
            return console.nextInt();
        }
        console.nextLine(); // discard the line and try again
        System.out.print(", please re-enter the hours again:");
    }
}
Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075