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

Unable to call back the name of the method I am while in it

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

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

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

else 子句中的 "mathsChoice();" 导致错误: "Unreachable code"

mathsChoice();

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

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

它告诉你 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();

}