7

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

2 Answers2

12

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

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • 4
    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 http://stackoverflow.com/questions/1601246/java-scripting-api-how-to-stop-the-evaluation . – johusman Jul 20 '12 at 10:25
  • I see your point. In this case, xyz should be matched using regex, to ensure it contains only numbers and mathematical operators – Anirudh Ramanathan Jul 20 '12 at 10:42
3

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

Elchin
  • 584
  • 6
  • 19
  • @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. – Marko Topolnik Jul 20 '12 at 10:23
  • 1
    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. – Elchin Jul 20 '12 at 10:25
  • 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. – Marko Topolnik Jul 20 '12 at 10:29