由于项目需要从服务器端传来一个计算公式,客户端根据公式计算得到值,故而学习了一下Jep。
如果是一般公式,使用Jep很容易实现计算得到结果。
String str = "6+7+8-9"; Jep jep = new Jep(); jep.parse(str); System.out.println(jep.evaluate());
默认情况下,Jep支持的符号列表如下:
Double | Complex | String | Vector | ||
Power | ^ | ||||
Boolean Not | ! | ||||
Unary Plus, Unary Minus | +x, -x | ||||
Dot product, cross product | ., ^^ | ||||
Modulus | % | ||||
Division | / | ||||
Multiplication | * | ||||
Addition, Subtraction | +, - |
(only +) |
|||
Less or Equal, More or Equal | <=, >= | ||||
Less Than, Greater Than | <, > | ||||
Not Equal, Equal | !=, == | ||||
Boolean And | && | ||||
Boolean Or | || | ||||
Assignment | = |
但是一般符号满足不了需求,公式中有比如 x++与a>b?c:d之类的公式,默认明显不支持。
支持java分格公式:
String str = "3>4?1:2"; Jep jep = new Jep(); jep.setComponents(new StandardConfigurableParser(),new JavaOperatorTable()); jep.parse(str); System.out.println(jep.evaluate());
上面代码额外支持的操作符如下:
Standard symbol |
Bitwise OperatorTable |
Java OperatorTable |
Arguments | |
---|---|---|---|---|
Bitwise and | & | Integer | ||
Bitwise or | | | Integer | ||
Bitwise xor | ^* | Integer | ||
Bitwise complement |
|