Java Algorithms How to - Convert mathematical string to int








Question

We would like to know how to convert mathematical string to int.

Answer

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/*from w  w  w  . j  av  a2  s.com*/
public class Main {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.put("a", 1);
    engine.put("b", 2);
    try {
      String expression = "(a + b) > 2";
      Object result = engine.eval(expression);
      System.out.println(expression + " ? " + result);
    } catch (ScriptException se) {
      se.printStackTrace();
    }
  }
}

The code above generates the following result.