Java string for math equation

I need to implement the function public int eval(String infix) {...} and when I use it as follows:

 eval("3+2*(4+5)") 

I have to get 21.

An arithmetic expression may contain "+", "*" and parentheses.

So how can I convert this to a mathematical equation? I can not use non-standard libraries.

UPDATE: Solution found.

These are 2 ways: Polish naming and using ScriptEngine.


+4
source share
3 answers

Believe it or not, with JDK1.6 you can use the built-in Javascript engine. Customize according to your needs.

Make sure you have the import ...

 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)); 
+10
source

Well, firstly, you want to tokenize the string. In essence, separate each element. Separate operations from individual numbers and save them in something (possibly a list). Then just do the operations based on the order of operations.

Thus, the pseudocode will look something like this:

 public int eval(String infix) { create a list of all the elements identify which operations you would want to do first perform the operations and simplify the list (eg if 5x4 were inside parantheses, remove the parantheses and replace it overall with 20.) continue the simplification until you have a final result return the result } 

There are probably much better ways to do this, but here is one solution.

+2
source
  static int eval(String infix) { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String stringResult; try { stringResult = engine.eval(infix).toString(); double doubleResult = Double.parseDouble(stringResult); int result = (int) doubleResult; return result; } catch (ScriptException ex) { Logger.getLogger(Ukol4a.class.getName()).log(Level.SEVERE, null, ex); } return(1); } 
0
source

All Articles