Java字符串到数学方程

我需要实现函数public int eval(String infix) {...} ,当我像这样使用它时:

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

我必须得到21。

算术表达式可以包含’+’,’*’和括号。

那么,我怎样才能将其转换为数学方程? 我不能使用非标准的库。

更新:找到解决方案。

它是2种方式:波兰表示法和使用ScriptEngine。


信不信由你,使用JDK1.6,您可以使用内置的Javascript引擎。 定制以满足您的需求。

确保你有这些import……

 import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; 

码:

 ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String infix = "3+2*(4+5)"; System.out.println(engine.eval(infix)); 

首先,你想要标记字符串。 基本上,将每个元素分开。 将操作与单个数字分开,并将它们存储在某些内容中(可能是列表)。 然后根据操作顺序进行操作。

所以伪代码就像这样:

 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 } 

可能有更好的方法来做到这一点,但这是一个解决方案。

  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); }