Is it possible to pass arithmetic operators to a method in java?

Posted by drJames on Stack Overflow See other posts from Stack Overflow or by drJames
Published on 2010-05-25T06:23:16Z Indexed on 2010/05/30 8:32 UTC
Read the original article Hit count: 168

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about operators