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

Jam*_*s T 29 java math operators

现在我将不得不写一个看起来像这样的方法:

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...";
        }
}
Run Code Online (Sandbox Code Playgroud)

如果我能编写更像这样的代码会很好:

public String Calculate(String Operator, Double Operand1, Double Operand2)
{
       return String.valueOf(Operand1 Operator Operand2);
}
Run Code Online (Sandbox Code Playgroud)

所以运算符会替换算术运算符(+, - ,*,/ ...)

有谁知道这样的东西在java中是否可行?

Jon*_*eet 42

不,你不能用Java做到这一点.编译器需要知道运算符正在做什么.你可以做的是一个枚举:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public String calculate(Operator op, double x1, double x2)
{
    return String.valueOf(op.apply(x1, x2));
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

String foo = calculate(Operator.ADDITION, 3.5, 2);
// Or just
String bar = String.valueOf(Operator.ADDITION.apply(3.5, 2));
Run Code Online (Sandbox Code Playgroud)

  • @aioobe:是的,我只是得到了标识符,但错过了实施.@Ashsish:是的,如果所有值都覆盖它,它们就可以. (3认同)

pol*_*nts 10

Java中的方法参数必须是表达式.运算符本身不是表达式.这在Java中是不可能的.

当然,您可以传递enum代表这些运算符的对象(可能是常量),并相应地执行操作,但您不能将运算符本身作为参数传递.


其他提示

由于您刚刚开始使用Java,因此最好尽早掌握这些信息以简化您的未来发展.

  • 方法名称以小写开头:calculate而不是Calculate
  • 变量名以小写开头:operator而不是Operator
  • Double是一个引用类型,原始类型的框double.
    • Effective Java 2nd Edition,Item 49:首选原始类型为盒装基元
  • 不要return "error...".代替,throw new IllegalArgumentException("Invalid operator");

也可以看看


Tho*_*ler 6

使用回调接口只有一种繁琐的方法。就像是

interface Operator {
    public Double do(Double x, Double y);
}
Run Code Online (Sandbox Code Playgroud)

然后你实现你需要的操作符:

Operator plus = new Operator() {
    public Double do(Double x, Double y) {
        return x + y;
    }
};
Run Code Online (Sandbox Code Playgroud)

你的泛型方法需要一个 Operator 和两个参数:

public String Calculate(Operator operator, Double x, Double y) {
    return String.valueOf( operator.do(x, y) );
}
Run Code Online (Sandbox Code Playgroud)

如果您只需要较小的固定数量的运算符,您也可以使用枚举而不是接口。

  • 这是。特别是因为您可以将匿名类用于一次性运算符。 (2认同)