由于项目需要从服务器端传来一个计算公式,客户端根据公式计算得到值,故而学习了一下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 | ~ |
|
| Integer |
Leftshift | << |
|
| Integer |
Signed rightshift | >> |
|
| Integer |
Unsigned rightshift | >>> |
|
| Integer |
Pre-increment/decrement | ++x, --x |
| Double variable | |
Post-increment/decrement | x++, x-- |
| Double variable | |
Conditional | ?: |
| Double | |
Assignment | +=, -=, *=, /=, %= |
| Double | |
Bitwise assignment | &=, |=, ^=, <<=, >>=, >>>= |
| Integer |
公式里一般不会全是常量,需要对公式里的变量赋值:
String str = "a>b?1:2";
Jep jep = new Jep();
jep.setComponents(new StandardConfigurableParser(),new JavaOperatorTable());
jep.addVariable("a", 3);
jep.addVariable("b", 4);
jep.parse(str);
System.out.println(jep.evaluate());
有些字符是保留作为默认值的,不能当做变量:
pi | 3.1415... The ratio of the circumference of a circle to its diameter (Math.PI ) |
e | 2.718... Euler's constant in double precision (Math.E) |
true | The boolean constant (Boolean.TRUE) |
false | The boolean constant (Boolean.FALSE) |
i | The complex imaginary unit |
Jep还支持自定义公式、使用复杂的数学公式.....。由于上面已经满足项目要求,并且这玩意没源码,方法都要一个个试过去,比较耗时,故而没继续试下去。
Jep开发包及文档:点击打开链接