0

The purpose of this was to ensure that the user does not receive any mismatch errors. Every time they enter a String by accident, I want the program to say "Sorry, please choose exercises from above" and give them the option to type an answer again without crashing. Currently, if the user types in a string, the loop skips the if statement and continues onto the else statement for ever until you manually terminate it.

int program = 0;    
System.out.println("Enter 1 for Vocabularly exsersises, 2 for Grammer Exercises and 3 for other");

    while (input.hasNext()) {

        if (input.hasNextInt()) 
            program = input.nextInt() ; 
        else 
            System.out.println("Sorry, please choose exercises from above");
    }
1
  • You might want to use a do-while loop instead. Commented May 8, 2014 at 1:34

2 Answers 2

3

You need to take the bad input or skip it:

//...
} else {
    System.out.println(...);
    input.nextLine();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Don't use a while loop for this. Instead use a do while loop.

Here is something I would do

int program;
System.out.println("Enter 1 for Vocabularly exsersises, 2 for Grammer Exercises and 3 for other");
do {
    try {
       program = input.nextInt();
    } catch (Exception e) {
       System.out.println("Sorry, please choose exercises from above");
    }
}while(program != null);

The do while loop is usefulwhen you do notknow what the user will enter yet.

The try catch statement will catch an error; in this case if the user tries to enter a string or char value. Try looking into try catch a little more. It will make programming a lot easier.

1 Comment

Using exceptions to catch cases rather than hasNextInt is exactly what you do not want to do. Also, program can never be null, as it is an int, so that loop would never end.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.