是否可以将算术运算符传递给java中的方法? [英] Is it possible to pass arithmetic operators to a method in java?

查看:124
本文介绍了是否可以将算术运算符传递给java中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Right now I'm going to have to write a method that looks like this:

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...";
        }
}

如果我能编写更多代码,那就太好了像这样:

It would be nice if I could write the code more like this:

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

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

So Operator would replace the Arithmetic Operators (+, -, *, /...)

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

Does anyone know if something like this is possible in java?

推荐答案

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

No, you can't do that in Java. The compiler needs to know what your operator is doing. What you could do instead is an enum:

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

然后您可以编写如下方法:

You can then write a method like this:

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中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆