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 14:23

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

hope that helped

查看更多
梦寄多情
3楼-- · 2018-12-31 14:23

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).

http://mathparser.org/

http://mathparser.org/mxparser-tutorial/

Please find below a few examples to have more clear view on the syntax.

Example 1 - simple formula

Expression e = new Expression("2+3");
double v = e.calculate();

Example 2 - built-in function

Expression e = new Expression("2+sin(3)");
double v = e.calculate();

Example 3 - built-in constants

Expression e = new Expression("2+sin(pi)");
double v = e.calculate();

Example 4 - user defined arguments and constants

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

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

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

Best regards,

LK

查看更多
低头抚发
4楼-- · 2018-12-31 14:25

You can use the ScriptEngine class and evaluate it as a javascript string

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 :

   eval('var aa=5+4*(7-15)')
   aa // -27

There may be a better way, but this one works.

查看更多
一个人的天荒地老
5楼-- · 2018-12-31 14:25
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;
}
查看更多
登录 后发表回答