Is it possible to pass arithmetic operators to a m

2020-01-23 07:24发布

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 (+, -, *, /...)

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

8条回答
家丑人穷心不美
2楼-- · 2020-01-23 07:49

Method arguments in Java must be expressions. An operator by itself is not an expression. This is not possible in Java.

You can, of course, pass objects (maybe enum constants) that represents those operators, and act accordingly, but you can't pass the operators themselves as parameters.


Additional tips

Since you're just starting Java, it's best to ingrain these informations early on to ease your future development.

  • Method names starts with lowercase: calculate instead of Calculate
  • Variable names starts with lowercase: operator instead of Operator
  • Double is a reference type, the box for primitive type double.
    • Effective Java 2nd Edition, Item 49: Prefer primitive types to boxed primitives
  • Don't return "error...". Instead, throw new IllegalArgumentException("Invalid operator");

See also

查看更多
ら.Afraid
3楼-- · 2020-01-23 07:51

No this is not possible in this way.

You will need a parser to do what you want, and this can be cumbersome.

You're probably asking the wrong question, since you are getting the wrong answer.

If you are looking for a mathematical parser you might want to take a look at this project on SF: http://sourceforge.net/projects/jep/

There might be some answers in this.

查看更多
我想做一个坏孩纸
4楼-- · 2020-01-23 07:55

You can't pass operators directly. You could use functors.

public double Calculate(BinaryFunction<Double, Double, Double> op, double Operand1, double Operand2)
{
  return (double)op.evaluate(Operand1, Operand2);
}
查看更多
成全新的幸福
5楼-- · 2020-01-23 07:57

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

And call it like this:

String foo = calculate(Operator.ADDITION, 3.5, 2);
// Or just
String bar = String.valueOf(Operator.ADDITION.apply(3.5, 2));
查看更多
ゆ 、 Hurt°
6楼-- · 2020-01-23 07:57

There's only the cumbersome way of doing it with a callback interface. Something like

interface Operator {
    public Double do(Double x, Double y);
}

Then you implement the operators you need:

Operator plus = new Operator() {
    public Double do(Double x, Double y) {
        return x + y;
    }
};

And your generic method takes an Operator and the two arguments:

public String Calculate(Operator operator, Double x, Double y) {
    return String.valueOf( operator.do(x, y) );
}

You could also use an enum instead of an interface if you only need a smaller, fixed number of operators.

查看更多
forever°为你锁心
7楼-- · 2020-01-23 08:03

You can either

  1. Use a functional language for JVM to implement this part of your code (clojure, scala et el), wrap lambda functions around math operators and pass those functions as parameters

  2. Get an expression evaluator for Java like http://www.singularsys.com/jep/ (and there must be many free alternatives as well)

查看更多
登录 后发表回答