由于项目需要从服务器端传来一个计算公式,客户端根据公式计算得到值,故而学习了一下Jep。
如果是一般公式,使用Jep很容易实现计算得到结果。
[java] view plaincopy
- 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分格公式:
[java] view plaincopy
- 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 |
公式里一般不会全是常量,需要对公式里的变量赋值:
[java] view plaincopy
- 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 |