Java try for for while while循环不循环

时间:2016-03-21 15:38:55

标签: java do-while

在尝试使用try catch for while 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.");
    }

我想做的while while循环是当用户输入6以外的任何终止时,它将继续提示用户输入。对于每种情况,它将采用某种方法。

然后,我尝试为InputMismatchException尝试catch,因为我的Scanner从用户输入获取整数。但是,在我输入字母而不是整数之后,程序才自行终止。我想在用户输入字母表时这样做,它会继续提示用户输入正确的信息。

有什么想法吗?提前谢谢。

我在考虑是否应该再做一次包装整个try catch?

2 个答案:

答案 0 :(得分:4)

喜欢:

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

如果用户输入无效输入,它将转到catch块并继续循环。删除外部try catch块。它不是必需的

答案 1 :(得分:0)

要处理字符和无效数字,您可以执行以下操作:

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