无法回拨我在其中的方法的名称

时间:2017-09-04 22:28:37

标签: java methods callback restart

我正在制作简单的计算器程序,最初只是要求加法,减法和除法的数字。 如果他们输入的数字不是1,2或3,我想创建一个IOException,然后调用该方法以允许用户再次被问到相同的问题。

也许我错过了一些明显的东西。任何帮助赞赏。谢谢。 ((假设扫描仪和所有其他功能都正常工作))

n=9

“mathsChoice();”在else子句中导致错误: “无法访问的代码”

public static void mathsChoice() throws IOException{
        System.out.println("'1' for Addition, '2' for Subtraction, '3' for Division");
        int resChoice = scanner.nextInt();
        if (resChoice == 1){
            additionMethod();
        }else if (resChoice == 2){
            subtractionMethod();
        }   else if (resChoice == 3){
            divisionMethod();
        }else {
              throw new IOException("Not valid, try again.");
              mathsChoice();
            }
        }

2 个答案:

答案 0 :(得分:1)

当你退出IOException方法退出时,永远不会到达mathsChoice();行。

您可能希望将其更改为简单的打印输出而不是异常。 System.out.println("Not valid, try again.");

答案 1 :(得分:1)

它告诉你mathsChoice()没有机会执行。在那个特定的块中,你总是抛出一个异常,它将终止程序执行,程序将永远不会到达这一行mathsChoice()

你应该在关闭else块后调用mathsChoice()

public static void mathsChoice() throws IOException{
        System.out.println("'1' for Addition, '2' for Subtraction, '3' for Division");
        int resChoice = scanner.nextInt();
        if (resChoice == 1){
            additionMethod();
        }else if (resChoice == 2){
            subtractionMethod();
        }   else if (resChoice == 3){
            divisionMethod();
        }else {
              throw new IOException("Not valid, try again.");
        }
     mathsChoice();

}