简体   繁体   中英

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

You need to take the bad input or skip it:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM