Question

I have the following code including two operands and one operands converted from objects. Now I would like to merge them to an expression so that I can get a final answer. For example, the method receives 2,3,* and converts it to 2*3 and returns 6. Is there an easy way of solving this without using a lot of if and else if to check if its +,-,*,/ and so on.

private long calculateExpression(Object op1, Object op2, Object op){
    long operand1 = Long.parseLong(String.valueOf(op1));
    long operand2 = Long.parseLong(String.valueOf(op2));
    Operator operator = Operator.toOperator(String.valueOf(op));

    return answer;
}
Was it helpful?

Solution

if you are using jdk 6+ you can use the scriptengine for this, like

private long calculateExpression(Object op1, Object op2, Object op) throws ScriptException{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String expression = "" + op1 + op + op2;
    Integer answer = (Integer) engine.eval(expression);
    return answer.longValue();
}

OTHER TIPS

You cannot convert Strings directly to operators. At some point you would have to add the if and else if cases. You could create your own Operator-Class and use its methods to parse the String, but that would only shift the if and else if cases to that Class.

EDIT: I have to edit, because I'm not able to comment yet ...

The answer provided by Syam S seems valid. But you have to alter the line

Integer answer = (Integer) engine.eval(expression);

to

Double answer = (Double) engine.eval(expression);

then it should work.

From the example on Nashorn

package sample1;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class Hello {

  public static void main(String... args) throws Throwable {
    ScriptEngineManager engineManager = 
new ScriptEngineManager();
    ScriptEngine engine = 
engineManager.getEngineByName("nashorn");
    engine.eval("function sum(a, b) { return a + b; }");
    System.out.println(engine.eval("sum(1, 2);"));
  }
}

You can adapt this to evaluate an expression at run time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top