gpt4 book ai didi

java - 是否可以将算术运算符传递给java中的方法?

转载 作者:IT老高 更新时间:2023-10-28 21:14:19 24 4
gpt4 key购买 nike

现在我将不得不编写一个如下所示的方法:

public String Calculate(String operator, double operand1, double operand2)
{

if (operator.equals("+"))
{
return String.valueOf(operand1 + operand2);
}
else if (operator.equals("-"))
{
return String.valueOf(operand1 - operand2);
}
else if (operator.equals("*"))
{
return String.valueOf(operand1 * operand2);
}
else
{
return "error...";
}
}

如果我能把代码写成这样就好了:

public String Calculate(String Operator, Double Operand1, Double Operand2)
{
return String.valueOf(Operand1 Operator Operand2);
}

因此运算符将替换算术运算符(+、-、*、/...)

有谁知道在java中这样的事情是否可行?

最佳答案

不,你不能在 Java 中做到这一点。编译器需要知道您的运算符(operator)在做什么。你可以做的是一个枚举:

public enum Operator
{
ADDITION("+") {
@Override public double apply(double x1, double x2) {
return x1 + x2;
}
},
SUBTRACTION("-") {
@Override public double apply(double x1, double x2) {
return x1 - x2;
}
};
// You'd include other operators too...

private final String text;

private Operator(String text) {
this.text = text;
}

// Yes, enums *can* have abstract methods. This code compiles...
public abstract double apply(double x1, double x2);

@Override public String toString() {
return text;
}
}

然后你可以写一个这样的方法:

public String calculate(Operator op, double x1, double x2)
{
return String.valueOf(op.apply(x1, x2));
}

然后这样调用它:

String foo = calculate(Operator.ADDITION, 3.5, 2);
// Or just
String bar = String.valueOf(Operator.ADDITION.apply(3.5, 2));

关于java - 是否可以将算术运算符传递给java中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2902458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com