I need to implement function public int eval(String infix) {...}
and when I use this like this:
eval("3+2*(4+5)")
I must receive 21.
The arithmetic expression can contain '+', '*' and parentheses.
So, how can I convert this to math equation? I can't use non-standard libs.
UPDATE: Solution found.
It is 2 way: Polish Notation and using ScriptEngine.
To evaluate mathematical expression in String, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance.
Here's how an arithmetic expression is parsed. A pointer is started at the left and is iterated to look at each character. It can be either a number(always a single-digit character between 0 and 9) or an operator (the characters +, -, *, and /). If the character is a number, it is pushed onto the stack.
println(toString()) in display() .
Believe it or not, with JDK1.6, you can use the built-in Javascript engine. Customise to suit your needs.
Make sure you have these imports...
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
Code:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String infix = "3+2*(4+5)";
System.out.println(engine.eval(infix));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With