java—无法回调我所在的方法的名称

abithluo  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(257)

我正在做一个简单的计算器程序,最初只是简单地要求一个关于加法,减法和除法的数字。如果他们输入的数字不是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(); } } “mathschoice();”在else子句中导致错误:“unreachable code”

mathsChoice();
svdrlsy4

svdrlsy41#

当你扔掉 IOException 方法退出,并且 mathsChoice(); 永远达不到底线。
您可能希望将其更改为简单的打印输出,而不是异常。 System.out.println("Not valid, try again.");

efzxgjgh

efzxgjgh2#

它告诉你 mathsChoice() 从来没有被处决的机会。在那个特定的块中,你总是抛出一个异常,它将终止程序的执行,而程序永远不会到达这一行 mathsChoice() 你应该把 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();

}

相关问题