How to parse a mathematical expression given as a

2018-12-31 13:41发布

This question already has an answer here:

Is there a way in Java to get the result from this mathematical expression:

String code = "5+4*(7-15)";

In other hand what's the best way to parse an arithmetic expression?

10条回答
临风纵饮
2楼-- · 2018-12-31 13:58

There is no direct support in the Java SDK for doing this.

You will either have to implement it yourself (possibly using a parser generator such as JavaCC), or use an existing library.

One option would be JEP (commercial), another JEval (free software).

查看更多
泪湿衣
3楼-- · 2018-12-31 14:02

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?

Take a look at: Scripting for the Java Platform.

查看更多
荒废的爱情
4楼-- · 2018-12-31 14:14

There is no builtin way of doing that. But you can use one of the many many open source calculators available.

查看更多
素衣白纱
5楼-- · 2018-12-31 14:16

You can pass it to a BeanShell bsh.Interpreter, something like this:

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.

查看更多
美炸的是我
6楼-- · 2018-12-31 14:16

You coul use that project

How to use:

double result = 0;
String code = "5+4*(7-15)";
try {
    Expr expr = Parser.parse(code);
    result = expr.value();
} catch (SyntaxException e) {
    e.printStackTrace();
}
System.out.println(String.format("Result: %.04f", result));
查看更多
泛滥B
7楼-- · 2018-12-31 14:18

There's a commercial tool called formula4j that does that job.

To take your example expression, it would be evaluated like this using formula4j:

Formula formula = new Formula("5+4*(7-15)");

Decimal answer = formula.getAnswer(); //-27

查看更多
登录 后发表回答