Sathoshi K
Sathoshi K

Reputation: 203

While Loop is skipping Satements

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");
    }

Upvotes: 0

Views: 75

Answers (2)

user3614562
user3614562

Reputation:

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.

Upvotes: 0

Rogue
Rogue

Reputation: 11483

You need to take the bad input or skip it:

//...
} else {
    System.out.println(...);
    input.nextLine();
}

Upvotes: 3

Related Questions