问题
Javax ScriptEngine and JEval works similarly, you input an string and send it to be evaluated, and it will return you the result of it:
In ScriptEngine (almost the same in JEval):
System.out.println(engine.eval("2*3+4"));
will result in:
10.0
But when I try to make it an exponential:
System.out.println(engine.eval("2^3+4"));
will result in:
5.0
But it really should result in 12 (2^3 = 8, 8+4=12), so my question is how can I set it up in a way that the string which the will be all the whole equation, will evaluate supporting the exponential, and result correctly?
Should I use another library?
回答1:
^
is the XOR operand, your string means 2 XOR 3 + 4
, which in facts evaluates to 1 + 4
.
You have to use
Math.pow(2,3) + 4
This is my code:
System.out.println(engine.eval("Math.pow(2,3) + 4"));
Output:
12.0
来源:https://stackoverflow.com/questions/18836358/how-to-evaluate-string-that-have-exponential