0

Im trying to check whether the input from the User is an int or not.

Heres my code so far:

static int readInt(Scanner userInput) {
    int intValue = 0;

    try {
    System.out.print("Please enter a number:");
    intValue = Integer.parseInt(userInput.nextLine());


    } catch (NumberFormatException ex) {
    Input.readInt(userInput);

    }
    return intValue;
}

The problem is: if I first give it input which is not a number and then after that i give it a number it always returns 0. If i give it a number the first attempt it returns the number I have given it.

What am I missing? Thanks in advance

edit: Im only allowed to use Integer.parseInt and Exceptions.

3
  • 3
    You are not assigning the return value of Input.readInt(userInput); to your intValue Commented Nov 22, 2017 at 11:02
  • Consider wrapping the input code in while-loop to ensure that the program only continues forward when valid input has been received. Commented Nov 22, 2017 at 11:03
  • If you're only allowed to use Integer.parseInt and Exceptions, please edit your question and add this requirement. Commented Nov 22, 2017 at 11:09

3 Answers 3

1

To avoid your problem, in the catch block you need to assign this Input.readInt(userInput) to your variable. like this :

intValue  = Input.readInt(userInput);
Sign up to request clarification or add additional context in comments.

Comments

0

It looks like you are not setting the variable in the catch

intValue = Input.readInt(userInput);

1 Comment

That solved it, thanks! so I dont have to put "Input.readInt(userInput);" in my catch then at all, right?
0

Recursion is overhead here. use loop:

Integer result = null;
do {
    System.out.print("Please enter a number:");
    try {
        result = Integer.parseInt(userInput.nextLine());
    } catch (NumberFormatException ex) {
        System.out.print("Not a number");
    }
} while(result==null);
return result;

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.