0

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;
}
Markus
  • 149
  • 1
  • 8
  • What is the `Operator` class? Presumably this is some custom or third-party library code? I expect it has an `execute` method (or something like that) that takes the operands and returns the result? – stridecolossus Apr 29 '14 at 13:37
  • No short, no. You can call JavaScript to do the evaluation instead. – Peter Lawrey Apr 29 '14 at 13:44

3 Answers3

2

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();
}
Syam S
  • 8,421
  • 1
  • 26
  • 36
1

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.

EngJon
  • 987
  • 8
  • 20
  • Depends what `Operator` is, if it's an enum then `Operator.valueOf()` can be used to 'parse' the operator and then invoke it on the two arguments. – stridecolossus Apr 29 '14 at 13:45
  • I assumed that Operator is a class created by Markus himself and has to be done – EngJon Apr 29 '14 at 13:52
0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130