Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I convert a string to a math operation in java?

can I convert a string like "3*3+3" to math operation in java??

like image 527
Mohamed Magdy Hassan Avatar asked Jul 20 '12 10:07

Mohamed Magdy Hassan


2 Answers

Evaluate it is as JavaScript using ScriptEngine

String xyz = "3*3+3";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("JavaScript");        
Object result = se.eval(xyz);

Reference: Documentation

like image 86
Anirudh Ramanathan Avatar answered Sep 21 '22 22:09

Anirudh Ramanathan


There is no built-in function for that, you would have to implement a parser. However you could also look up for ready project, such as: http://sourceforge.net/projects/jep/ or http://code.google.com/p/symja/wiki/MathExpressionParser

like image 27
Elchin Avatar answered Sep 22 '22 22:09

Elchin