can I convert a string like "3*3+3" to math operation in java??
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
2 Comments
johusman
This is potentially very dangerous, and assumes that you trust the source of the xyz string completely. This allows the execution of any JavaScript. For example, try settings xyz to "while(true);". See stackoverflow.com/questions/1601246/… .
Anirudh Ramanathan
I see your point. In this case, xyz should be matched using regex, to ensure it contains only numbers and mathematical operators
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
3 Comments
Marko Topolnik
@BrianAgnew Just look at the top-voted answer. Except if you really believe the question is about getting a representation of the expression, which I doubt. But no need to argue on that.
Elchin
you mean JavaScript Engine? It works, but I think its too much of an overhead, and functionality is limited. Its better to use specialized libraries.
Marko Topolnik
If you need it, then yes. OP didn't motivate it, however, and the claim that there is no built-in function is, well, misleading---except if you choose to interpret the question to be about the representation of the expr, not its result.