简体   繁体   English

Java try for for while while循环不循环

[英]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: 我在尝试尝试catch for do while循环时遇到了一些问题:

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. 我想为do while循环做的是当用户输入6以外的任何终止时,它将继续提示用户输入。 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. 然后,我尝试为InputMismatchException尝试catch,因为我的Scanner从用户输入获取整数。 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? 我在想是否应该再做一次包装整个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. 如果用户输入无效输入,它将转到catch块并继续循环。 Remove the outer try catch block. 删除外部try catch块。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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