Java Algorithms How to - Evaluate math expressions in String








Question

We would like to know how to evaluate math expressions in String.

Answer

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
// ww  w  .j  a  v  a 2s .com
public class Main {
  public static void main(String[] args) throws Exception {
    // create a script engine manager
    ScriptEngineManager factory = new ScriptEngineManager();
    // create a JavaScript engine
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    // evaluate JavaScript code from String
    Object obj = engine.eval("1+2");
    System.out.println(obj);
  }
}

The code above generates the following result.