0

I need to evaluate " (num1+ num2) < num 3 " expression in boolean format Example :

String str = "(24+3) < 4";

Have to evaluate above str to Boolean if true or false and then use the final Boolean value inside if () condition.

I do not want to extract individual characters, convert into int and then keep evaluating each sub expressions.

Nilesh Thakkar
  • 1,442
  • 4
  • 25
  • 36
Ranjan Kumar
  • 107
  • 1
  • 10
  • then how do you expect to solve this? "24" and 24 have completely different meanings and values. you can't run numeric comparisons on Strings and expect the JVM to know what you want with it. – Stultuske Apr 10 '15 at 11:30
  • Already discussed here http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java – Himanshu Ahire Apr 10 '15 at 11:35

2 Answers2

3

You can use the javascript engine but I think it's too much for this:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String str = "(24+3) < 4";
try {
    if (engine.eval(str)){
        ...
    }
} catch (ScriptException e) {
}
FuRioN
  • 623
  • 5
  • 12
1

And there's also a BeanShell (http://www.beanshell.org/):

    final Interpreter i = new Interpreter();

    try {
        Object res = i.eval("(24 + 3) < 4");
        System.out.println("Result is " + res);
    } catch (EvalError ex) {
        System.err.println("Error while evaluating expression: " + ex.getMessage());
    }
FlasH from Ru
  • 1,165
  • 2
  • 13
  • 19