Java 如何解析作为字符串给出的数学表达式并返回一个数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1432245/
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
How to parse a mathematical expression given as a string and return a number?
提问by Martijn Courteaux
Is there a way in Java to get the result from this mathematical expression:
Java 中有没有办法从这个数学表达式中得到结果:
String code = "5+4*(7-15)";
In other hand what's the best way to parse an arithmetic expression?
另一方面,解析算术表达式的最佳方法是什么?
采纳答案by Nick Holt
You can pass it to a BeanShellbsh.Interpreter
, something like this:
您可以将其传递给BeanShellbsh.Interpreter
,如下所示:
Interpreter interpreter = new Interpreter();
interpreter.eval("result = 5+4*(7-15)");
System.out.println(interpreter.get("result"));
You'll want to ensure the string you evaluate is from a trusted source and the usual precautions but otherwise it'll work straight off.
您需要确保您评估的字符串来自受信任的来源和通常的预防措施,否则它将直接起作用。
If you want to go a more complicated (but safer) approach you could use ANTLR(that I suspect has a math grammar as a starting point) and actually compile/interpret the statement yourself.
如果你想采用更复杂(但更安全)的方法,你可以使用ANTLR(我怀疑它有一个数学语法作为起点)并实际编译/解释语句。
回答by soulmerge
There is no builtin way of doing that. But you can use one of the many many open source calculatorsavailable.
没有内置的方法可以做到这一点。但是您可以使用众多可用的开源计算器之一。
回答by Andy
Probably not in as straight forward a manner as you are hoping!
可能不像您希望的那样直接!
But perhaps you could use a javax.script.ScriptEngine and treat the string as a ECMAScript expression, for example?
但也许您可以使用 javax.script.ScriptEngine 并将字符串视为 ECMAScript 表达式,例如?
Take a look at: Scripting for the Java Platform.
看一看:Java 平台的脚本。
回答by sleske
There is no direct support in the Java SDK for doing this.
Java SDK 中没有直接支持这样做。
You will either have to implement it yourself (possibly using a parser generator such as JavaCC), or use an existing library.
您要么必须自己实现(可能使用解析器生成器,例如 JavaCC),要么使用现有的库。
One option would be JEP(commercial), another JEval(free software).
回答by fasseg
i recently developed a expression parser and released it under the apache license. you can grab it at http://projects.congrace.de/exp4j/index.html
我最近开发了一个表达式解析器并在 apache 许可下发布了它。你可以在http://projects.congrace.de/exp4j/index.html获取它
hope that helped
希望有所帮助
回答by John O
There's a commercial tool called formula4jthat does that job.
有一个名为formula4j的商业工具可以完成这项工作。
To take your example expression, it would be evaluated like this using formula4j:
以您的示例表达式为例,它将使用公式4j进行如下评估:
Formula formula = new Formula("5+4*(7-15)");
Formula formula = new Formula("5+4*(7-15)");
Decimal answer = formula.getAnswer(); //-27
Decimal answer = formula.getAnswer(); //-27
回答by Jc Mi?arro
回答by Abdennour TOUMI
You can use the ScriptEngine class and evaluate it as a javascript string
您可以使用 ScriptEngine 类并将其评估为 javascript 字符串
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("5+4*(7-15)");
Indeed , yu should know that the result of the following instruction in javascript :
确实,你应该知道以下 javascript 指令的结果:
eval('var aa=5+4*(7-15)')
aa // -27
There may be a better way, but this one works.
可能有更好的方法,但这个方法有效。
回答by Semioniy
public static int calc(String string){
int result=0;
String numbers="0123456789";
String operations="+-/*";
for (int i=0;i<string.length();i++){
if (numbers.contains(string.charAt(i)+"")){
result=result*10+(Integer.parseInt(string.charAt(i)+""));
}
else {
if (string.charAt(i)=='+'){ result+=calc(string.substring(i+1));}
if (string.charAt(i)=='-'){ result-=calc(string.substring(i+1));}
if (string.charAt(i)=='*'){ result*=calc(string.substring(i+1));}
if (string.charAt(i)=='/'){ try{result/=calc(string.substring(i+1));}
catch (ArithmeticException e){
System.err.println("You cannot devide by Zero!");}
}
break;
}
}
return result;
}
回答by Leroy Kegan
Recently I was using very mature math expression parser library, open source, giving the same API for JAVA and .NET. The library name is mXparser. mXparser provides basic functionalities (simple formulas parsing and calculation) and more advanced ones (i.e. user defined arguments, functions). Additionally it is worth to notice that mXparser has rich built-in math collection (meaning operators, unary / binary / variadic functions, iterated operators such as summation and product).
最近我在使用非常成熟的数学表达式解析器库,开源,为 JAVA 和 .NET 提供相同的 API。库名称是 mXparser。mXparser 提供基本功能(简单的公式解析和计算)和更高级的功能(即用户定义的参数、函数)。此外值得注意的是,mXparser 具有丰富的内置数学集合(含义运算符、一元/二元/可变参数函数、求和和乘积等迭代运算符)。
https://mathparser.org/mxparser-tutorial/
https://mathparser.org/mxparser-tutorial/
Please find below a few examples to have more clear view on the syntax.
请在下面找到几个示例,以便更清楚地了解语法。
Example 1 - simple formula
示例 1 - 简单公式
Expression e = new Expression("2+3");
double v = e.calculate();
Example 2 - built-in function
示例 2 - 内置函数
Expression e = new Expression("2+sin(3)");
double v = e.calculate();
Example 3 - built-in constants
示例 3 - 内置常量
Expression e = new Expression("2+sin(pi)");
double v = e.calculate();
Example 4 - user defined arguments and constants
示例 4 - 用户定义的参数和常量
Argument x = new Argument("x = 5");
Constant a = new Constant("a = 2 + sin(3)");
Expression e = new Expression("a + x^2", x, a);
double v1 = e.calculate();
x.setArgumentValue(10);
double v2 = e.calculate();
Example 5 - user defined functions
示例 5 - 用户定义的函数
Function f = new Function("f(x,y) = x^2 + cos(y)");
Expression e = new Expression("f(10,pi) - 3", f);
double v = e.calculate();
Example 6 - user defined recursion
示例 6 - 用户定义的递归
Function factorial = new Function("fact(n) = if( n > 0; n*fact(n-1); 1)");
Expression e = new Expression("fact(10) - 10!", factorial);
double v = e.calculate();
Found recntly - in case you would like to try the syntax (and see the advanced use case) you can download the Scalar Calculatorappthat is powered by mXparser.
最近发现 - 如果您想尝试语法(并查看高级用例),您可以下载由 mXparser 提供支持的标量计算器应用程序。
Best regards
此致
LK
力劲