Back
I'm trying to write a Java routine to evaluate simple math expressions from String values like:
I want to avoid a lot of if-then-else statements. How can I do this?
On JDK1.6, you can try the built-in Javascript algo.
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)); } }
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));
}
31k questions
32.8k answers
501 comments
693 users