0

My method must request input from the user, check if it is an integer, and if it is return that integer. I attempted this using a try catch and the InputMismatchException.

I am running into an issue when it loops, if I input a non integer, it continuously spits out "Invalid input" "Enter an integer: " instead of actually asking for one.

public int getInteger(){
    Scanner i = new Scanner(System.in);
    int value = 0;

    for(boolean test = false; test == false;){
        try{
        System.out.println("Enter an integer: ");
        value = i.nextInt();

        test = true;
        return value;
        }
        catch(InputMismatchException e){System.out.println("Invalid input");}
    }
    return value;
} 
2
  • Solved my problem by initiating scanner i inside the for loop. Commented Oct 6, 2014 at 0:50
  • 2
    MattM - that is a bad solution. And not guaranteed to work. Commented Oct 6, 2014 at 0:53

2 Answers 2

3

You need a i.nextLine(); at the end of the loop.

    catch(InputMismatchException e){System.out.println("Invalid input");}
    i.nextLine();
}

What that does is reads the new line character, left unread by i.nextInt(), from the input stream. It's also the reason your i.nextInt() keeps tripping on the subsequent calls.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. If you want, you can also use nextLine() instead of nextInt() and parse the line using the Integer.parseInt() method.
0

I suggest you call hasNextInt() before nextInt() instead of trying to catch the Exception. Something like,

public int getInteger() {
    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        if (scan.hasNextInt()) {
            return scan.nextInt();
        } else {
            System.out.printf("%s is not an int%n", scan.nextLine());
        }
    }
    return -1;
}

1 Comment

Calling next() won't recover if the user entered something like "a b c" instead of a number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.