java - Evaluating a math expression given in string form -
i'm trying write java routine evaluate simple math expressions string
values like:
"5+3"
"10-40"
"10*3"
i want avoid lot of if-then-else statements. how can this?
with jdk1.6, can use 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)); } }
Comments
Post a Comment