How to evaluate a math expression given in string form?

Shah picture Shah · Aug 6, 2010 · Viewed 459.5k times · Source

I'm trying to write a Java routine to evaluate math expressions from String values like:

  1. "5+3"
  2. "10-40"
  3. "(1+10)*3"

I want to avoid a lot of if-then-else statements. How can I do this?

Answer

RealHowTo picture RealHowTo · Aug 6, 2010

With JDK1.6, you can use the built-in Javascript engine.

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

public class Test {
  public static void main(String[] args) throws ScriptException {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String foo = "40+2";
    System.out.println(engine.eval(foo));
    } 
}