【问题标题】:Retuning values inside if statements在 if 语句中重新调整值
【发布时间】:2021-05-28 02:36:20
【问题描述】:

我有这个代码;

public double equate(String type, double num1, double num2) {
    if (type.equals("Addition")) {
        return (num1 + num2);
    } else if (type.equals("Subtraction")) {
        return (num1 - num2);
    } else if (type.equals("Multiplication")) {
        return (num1 * num2);
    } else if (type.equals("Division")) {
        return (num1 / num2);
    }
}

我知道 return 语句应该在 if 语句之外,因为它不是块不起作用。我正在尝试使用一种在调用该方法时会根据用户偏好提供不同输出的方法。

感谢任何帮助。

【问题讨论】:

  • "我知道 return 语句应该在 if 语句之外" 这不是硬性规定
  • 如果你只有四个选择,把最后一个else if (type.equals("Division"))改成else。然后就可以了。
  • 哇,好的。谢谢,现在可以使用了。 @AKSingh
  • @JST 您还可以添加else { throw new IllegalArgumentException("Uknown type: " + type); },这将修复您丢失的返回,并且当传递的类型不是您期望的 4 个字符串之一时,您的方法会抛出错误/异常。跨度>
  • 如果您只是将最后一个else if 更改为else,任何不是“加法”、“减法”或“乘法”的类型都将被视为一个除法。所以equate("PopeyeTheSailor", 2.0, 1.0); 将被视为与equate("Division", 2.0, 1.0); 相同。如果这是您想要的行为,这当然取决于您

标签: java if-statement methods return


【解决方案1】:

不是直接的答案,而是一些替代方案:

普通的switch(switch语句)

public double equate(String type, double num1, double num2) {
    switch (type) {
        case "Addition": return (num1 + num2);
        case "Subtraction": return (num1 - num2);
        case "Multiplication": return (num1 * num2);
        case "Division": return (num1 / num2);
        default: throw new IllegalArgumentException(
                "Unrecognized type: " + type);
    }
}

switch 表达式(Java 12 中引入(预览功能))

public double equate(String type, double num1, double num2) {
    return switch (type) {
        case "Addition" -> (num1 + num2);
        case "Subtraction" -> (num1 - num2);
        case "Multiplication" -> (num1 * num2);
        case "Division" -> (num1 / num2);
        default -> throw new IllegalArgumentException(
                "Unrecognized type: " + type);
    };
}

还值得一提的是,与其使用 String 来表示类型,不如使用 enum 来表示 (IMO)

enum OperationType {
  ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION;
}
public double equate(OperationType type, double num1, double num2) {
    // any of given alternatives/answers, just change string into enum constant
    // e.g. case ADDITION: ...
    // or if (type == OperationType.ADDITION) {

【讨论】:

    【解决方案2】:

    您关于 if 内的 return is not allowed 的说法不正确。那里允许有返回值,但如果你所有的 if/elseif 都是假的,你还需要返回一些东西。

    您可以通过在 if 块中没有匹配项时返回异常来解决此问题。这使得在所有情况下,您在方法中都有一个有效的结束状态。

    public double equate(String type, double num1, double num2) {
        if (type.equals("Addition")) {
            return (num1 + num2);
        } else if (type.equals("Subtraction")) {
            return (num1 - num2);
        } else if (type.equals("Multiplication")) {
            return (num1 * num2);
        } else if (type.equals("Division")) {
            return (num1 / num2);
        } else {
            throw new IllegalArgumentException("Incorrect type provided " + type);
        }
    }
    

    或者,但不推荐在这种情况下,如果 if 块没有任何通过,您可以返回某种默认值

    【讨论】:

    • 建议:在错误信息中包含type,更容易调试/纠正/理解
    【解决方案3】:

    如果您声明您的函数返回double,那么它必须返回double,否则会抛出错误。

    如果类型不等于AdditionSubtractionMultiplicationDivision,则执行将运行到最后一个else if {} 块并且没有任何内容可返回。 (好像它正在返回 void。)因为它 void != double 函数无法编译。

    要解决这个问题,你需要处理错误的情况

    public double equate(String type, double num1, double num2) throws Exception {
    if (type.equals("Addition")) {
        return (num1 + num2);
    } else if (type.equals("Subtraction")) {
        return (num1 - num2);
    } else if (type.equals("Multiplication")) {
        return (num1 * num2);
    } else if (type.equals("Division")) {
        return (num1 / num2);
    }
    // If the function has not returned yet then type was not any of the valid choices
    throw new Exception("Invalid Type!");
    

    }

    或者如果你确定某个类型将始终有效,则更改最后一个块

    public double equate(String type, double num1, double num2) throws Exception {
    if (type.equals("Addition")) {
        return (num1 + num2);
    } else if (type.equals("Subtraction")) {
        return (num1 - num2);
    } else if (type.equals("Multiplication")) {
        return (num1 * num2);
        // by process of elimination, type must equal "Division" 
    } else {          
            return (num1 / num2);
        }
    }
    

    【讨论】:

      【解决方案4】:

      你可以将答案设置为另一个变量,然后返回该变量

      public double equate(String type, double num1, double num2) {
          double result = 0;
          if (type.equals("Addition")) {
              result = num1 + num2;
          } else if (type.equals("Subtraction")) {
              result = num1 - num2;
          } else if (type.equals("Multiplication")) {
              result = num1 * num2;
          } else if (type.equals("Division")) {
              result = num1 / num2;
          }
          return result;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多