Mireodon
Mireodon

Reputation: 185

nextInt() method of Scanner class does not ask me for input again in while loop?

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?

Upvotes: 0

Views: 182

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533880

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:");
    }
}

Upvotes: 1

Mark
Mark

Reputation: 5239

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;
}

Upvotes: 2

Related Questions