【问题标题】:How to catch an Error in a Switch statement when the user entered number doesn't exist当用户输入的数字不存在时如何在 Switch 语句中捕获错误
【发布时间】:2020-04-05 18:54:49
【问题描述】:

我正在尝试对我的程序进行错误证明,该程序基本上可以用作迷你计算器。但是我不知道如何编写一个“Catch”语句来检测用户何时输入一个不存在的案例编号,在我的案例中是任何负数或 > 4

        System.out.println("Hello user! Which operation would you like to use?");
        System.out.println("1) + \n2) - \n3) * \n4) /");


        Scanner operacijai = new Scanner(System.in);
        int operacija = operacijai.nextInt();


        int n=1;
        do {
        try {
            switch (operacija) {
            case 1:
                addingMethod();
                n=2;
                break;

            case 2:
                subtractingMethod();
                n=2;
                break;

            case 3:
                multiplyingMethod();
                n=2;
                break;

            case 4:
                dividingMethod();
                n=2;
                break;
                    }       
            }
            catch(Exception e) {
                System.out.print("Enter a correct number!");
            }

        } while(n==1);
        operacijai.close();

    } ```

【问题讨论】:

  • 在您的交换机上使用“默认”子句:w3schools.com/java/java_switch.asp
  • 让他们进入不是更容易吗? + 而不是 1? (你可以打开一个字符串)
  • @marcellorvalle 当我添加“默认”子句时,它会永远循环下去。
  • @AndyTurner 即使开关是 + - / * 我仍然想以某种方式捕捉错误的输入,以便程序返回开关并要求正确的输入。
  • @Glamy 当然。只是提一下让用户做“如果你想要X请输入Y”的心理体操不是很“防错”,如果他们可以直接输入“X”。

标签: java exception switch-statement


【解决方案1】:

您为什么要不必要地抛出Exception?我建议您只需在您的switch 中添加一个default 案例,并附上所需的错误消息。此外,将输入部分移动到循环内,以便它继续接受输入。

我还建议您使用nextLine() 而不是nextInt()。检查Scanner is skipping nextLine() after using next() or nextFoo()? 了解更多信息。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello user! Which operation would you like to use?");
        System.out.println("1) + \n2) - \n3) * \n4) /");
        Scanner operacijai = new Scanner(System.in);
        int operacija = 0, n = 1;
        boolean valid;
        do {
            do {
                valid = true;
                try {
                    operacija = Integer.parseInt(operacijai.nextLine());
                } catch (NumberFormatException e) {
                    System.out.println("Enter an integer only.");
                    valid = false;
                }
            } while (!valid);
            switch (operacija) {
            case 1:
                System.out.println("addingMethod()");
                n = 2;
                break;

            case 2:
                System.out.println("subtractingMethod()");
                n = 2;
                break;

            case 3:
                System.out.println("multiplyingMethod()");
                n = 2;
                break;

            case 4:
                System.out.println("dividingMethod()");
                n = 2;
                break;
            default:
                System.out.println("Invalid input");
            }
        } while (n == 1);
    }
}

示例运行:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
5
Invalid input

另一个示例运行:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()

【讨论】:

  • 但是你的答案中最重要的变化是你没有明确提到的:在循环中移动operacija =
  • 感谢@AndyTurner 的反馈。我忘了在解释中提到这一点。我现在已经做到了。
  • @AndyTurner 是的,我在循环中移动了 Scanner 变量,当我稍微考虑一下时,这是有道理的,但是现在当我第一次输入错误的输入时它什么也没说,但当我输入时它再次按预期工作。(如输入 5 一次,没有任何反应,再次输入 5,工作。)
  • @Glamy - 这个问题与stackoverflow.com/questions/13102045/… 有关。让我也用这些信息更新我的答案。
  • @ArvindKumarAvinash 您的回答很有帮助,但正如我之前评论的那样,它只会在我两次输入错误答案后打印出默认语句,这很奇怪......
【解决方案2】:

你也可以处理default中的用例 如何处理异常完全取决于您的用例,您还可以创建自定义异常并从默认值抛出 类似:

    System.out.println("Hello user! Which operation would you like to use?");
    System.out.println("1) + \n2) - \n3) * \n4) /");


    Scanner operacijai = new Scanner(System.in);
    int operacija = operacijai.nextInt();


    int n=1;
    do {
    try {
        switch (operacija) {
        case 1:
            addingMethod();
            n=2;
            break;

        case 2:
            subtractingMethod();
            n=2;
            break;

        case 3:
            multiplyingMethod();
            n=2;
            break;

        case 4:
            dividingMethod();
            n=2;
            break;
        default:
            System.out.print("Enter a correct number!")
            throw new CustomException();
        }       
      }
      catch(CustomException e) {
          System.out.print("Enter a correct number!");
      }

    } while(n==1);
    operacijai.close();

}

【讨论】:

  • 不要为您可以轻易检测到的东西抛出异常。这里的投掷和接球毫无用处。
【解决方案3】:

想出一个干净的方法来使用默认情况。

        System.out.println("Hello user! Which operation would you like to use?");
        System.out.println("1) + \n2) - \n3) * \n4) /");
            
        
        Scanner operacijai = new Scanner(System.in);
        int operacija;
        
        do {
            operacija = operacijai.nextInt();
            switch (operacija) {
            case 1:
                addingMethod();
                break;
                    
            case 2:
                subtractingMethod();
                break;
                
            case 3:
                multiplyingMethod();
                break;
                
            case 4:
                dividingMethod();
                break;
                
            default:
                    System.out.print("Enter a correct number!");
                
                    }       
    
        } while(operacija < 1 || operacija > 4);
        operacijai.close();
        
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多