java Java字符串到数学方程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13662001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java string to math equation
提问by JohnDow
I need to implement function public int eval(String infix) {...}
and when I use this like this:
我需要实现功能public int eval(String infix) {...}
,当我像这样使用它时:
eval("3+2*(4+5)")
I must receive 21.
我必须收到 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.
它有两种方式:波兰表示法和使用 ScriptEngine。
回答by xagyg
Believe it or not, with JDK1.6, you can use the built-in Javascript engine. Customise to suit your needs.
信不信由你,有了JDK1.6,你就可以使用内置的Javascript引擎了。定制以满足您的需求。
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));
回答by Clark
Well first off, you'd want to tokenize the string. Essentially, separate each element. Separate the operations from the individual numbers, and store them in something (maybe a list). Then just go through the operations based upon the order of operations.
首先,您想对字符串进行标记。本质上,将每个元素分开。将操作与单个数字分开,并将它们存储在某个东西中(可能是一个列表)。然后只需根据操作顺序进行操作即可。
So the pseudocode would be something like:
所以伪代码类似于:
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 (e.g. 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's one solution.
可能有更好的方法来做到这一点,但这里有一个解决方案。
回答by JohnDow
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);
}