fixing the java.util.InputMismatchException on second step of nextInt()

Viewed 38

I'm writing a very simple program and where I am getting 3 ints from a user and want to check to make sure they are all ints before storing them into seperate variables to process. The check I've used works on the first input but fails and throws the exception on the second two.

boolean properInt = scanner.hasNextInt();
    int largest = Integer.MAX_VALUE;
    boolean anError = false;


    while(properInt=false){
        anError=true;
        System.out.println("Invalid number...whole numeric values only");
    }

    while(properInt =true){

    int a= scanner.nextInt();
        System.out.println("you entered "+ a);
    int b = scanner.nextInt();
        System.out.println("you entered "+ b);
    int c= scanner.nextInt();
        System.out.println("you entered "+ c);

}

1 Answers

Reason is when you use any of the nextXxx(...), the scanner cursor is reset to where it was before the call. When you press 'enter' key after entering a valid number, scanner ignores the 'character' (enter). However, when you enter an invalid value, an exception is thrown and the enter key character is seen by the next 'nextInt' as another condition and so won't work.

I would suggest using nextLine and then Integer.ParseInt and catching NumberFormatException.

Also, your while loop check is incorrect.

properInt=false is a statement.

while(properInt==false) is a condition..

English is not my strength so if its confusing let me know.

Related