Search code examples
javavalidationuser-input

User inputs multiple values and "skips Validation"


I am just recreationally coding with a little program of mine and I discovered that I could effectively skip my validation by entering multiple values and placing a space in between them. For example, a snippet of my code is as follows:

while(counter == 0) {
    try{
        int choice = input.nextInt();
        System.out.println("Good job");
        ++counter;
    } catch(InputMismatchException Exception) {
        System.out.println("You did something wrong");
        input.next();
    }
}

when it asks for the user input, I can just type "h 4" and it will accept it, sure it will say "you did something wrong" but it will also display "good job". What do I need to do to get my code to take the entire line into account and display "you did something wrong" if the user were to do something such as this.

I had been making my program with the idea in mind that the user would only enter one piece of information such as "hello" or "4". I did not take into account that they could enter "hello 4" until just now and my program is now suffering a bit because of it.


Solution

  • You have to use nextLine to read the full line after a wrong input is given.

    So replace this:

    input.next();
    

    with this in your catch block:

    input.nextLine();
    

    Explanation:

    When you enter "h 4", input.next(); reads the "h" and leaves the "4", which is a good value since is parseable to int and int choice = input.nextInt(); reads this value when the loop starts again. Instead when you use readLine it will read the full wrong input "h 4" after displaying the message, loop again and wait until a new value is given.