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

Posted by user349611 on Stack Overflow See other posts from Stack Overflow or by user349611
Published on 2010-05-25T06:23:16Z Indexed on 2010/05/25 6:31 UTC
Read the original article Hit count: 140

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