简体   繁体   中英

Java try catch for do while loop not looping

I was having some problem when trying to do a try catch for do while loop:

try{
    do {
        System.out.println("Enter your option: ");
        choice = sc.nextInt();
        switch (choice) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                break;

        }
    } while (choice != 6);
    }catch(InputMismatchException e){
        System.out.println("Please enter option between 1-6.");
    }

What I am trying to do for the do while loop is when user entered anything other than 6 which is terminate, it will keep prompting for user input. For each case, it will go to certain method.

Then, I tried to do a try catch for InputMismatchException because my Scanner is taking integer from user input. However, after I entered alphabet instead of integer, the program just terminated itself. I am trying to do like when user entered alphabet, it will keep on prompting user for correct input.

Any ideas? Thanks in advance.

I was thinking if I should make another do while to wrap the entire try catch?

Do like :

try {
   choice = sc.nextInt();
} catch(InputMismatchException e){
        System.out.println("Please enter option between 1-6.");
        sc.next();
        continue;
    }

If user enters a invalid input it will go to the catch block and will continue the loop. Remove the outer try catch block. Its not required

To handle characters and and invalid numbers you could do something like this:

do {
    System.out.println("Enter your option: ");
    try{
      choice = sc.nextInt();
    catch(InputMismatchException e){
      choice = 0;
      sc.next();
    }
    switch (choice) {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;
        case 5:
            break;
        default:
            System.out.println("Please enter option between 1-6.");
            break;
       }
} while (choice != 6);

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