Issue
I have a string like the following:
String str = "4*5";
Now I have to get the result of 20
by using the string.
I know in some other languages the eval()
function will do this.
How can I do this in Java?
Solution
You can use the ScriptEngine
class and evaluate it as a Javascript string.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("4*5");
There may be a better way, but this one works.
Answered By - Jeff Storey
Answer Checked By - Marie Seifert (JavaFixing Admin)