7

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

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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/… .
I see your point. In this case, xyz should be matched using regex, to ensure it contains only numbers and mathematical operators
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

3 Comments

@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.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.