2

Whenever I try to run this loop, I receive:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at test.readNumber(Lab2.java:28)
    at test.go(Lab2.java:15)
    at test.main(Lab2.java:7)

I'm trying to repeatedly prompt the user until the keyboard input is positive. Can anyone tell me how I can go about doing that without running into error?

    public int readNumber() {
        int x = keyboard.nextInt();
        while (x < 0) {
            System.out.println("Please enter a positive number.");
            x = keyboard.nextInt();
        }   
        return x;
    }
2

4 Answers 4

3

It is always a good idea to check the docs. The exception is thrown if input data doesn't match the "Integer" pattern. Wrap input with try/catch:

public int readNumber() {
    int x = -1;
    while (x < 0) {
        System.out.println("Please enter a positive number.");
        try {
            x = keyboard.nextInt();
        } catch (java.util.InputMismatchException e) {
            // oops, wrong input
        }
    }   
    return x;
}
Sign up to request clarification or add additional context in comments.

1 Comment

breaks if initial input is not an int
1
public int readNumber() {
        int x = -1;
        do {
            try {
               System.out.println("Please enter a positive number.");
               x = keyboard.nextInt();
            } catch (InputMismatchException e) {
              // normally you always want to handle the exception but in this case it is okay because mismatched input is the same as a non-positive integer input
            }
        } while (x < 0);
        return x;
    }

Comments

0

You are either not supplying an integer or giving a value for an integer which is out of range.

1 Comment

You were right, turns out I was giving a value that was out of range. Thanks a lot!
0

You have to read the EOL after reading te int value.

public int readNumber() {
        int x = keyboard.nextInt();
        keyboard.readNextLine();
        while (x < 0) {
            System.out.println("Please enter a positive number.");
            x = keyboard.nextInt();
            keyboard.readNextLine();  
        }   
        return x;
    }

Comments

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.