Can I convert a string to a math operation in java?
Asked Answered
L

2

7

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

Lincolnlincolnshire answered 20/7, 2012 at 10:9 Comment(0)
W
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

Werbel answered 20/7, 2012 at 10:12 Comment(2)
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 #1601746 .Pleurisy
I see your point. In this case, xyz should be matched using regex, to ensure it contains only numbers and mathematical operatorsWerbel
H
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

Hebrews answered 20/7, 2012 at 10:12 Comment(3)
@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.Collective
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.Hebrews
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.Collective

© 2022 - 2024 — McMap. All rights reserved.