Java数学表示式解析工具- jeval

来源:互联网 发布:忽略的网络怎么恢复 编辑:程序博客网 时间:2024/05/19 11:45
这个包可以为我们提高高效的数学表达式计算。
举个例子:这个是我们策划给出的游戏命中率的一部份计算公式
是否命中=a命中率 – (b等级 – a等级) * (命中系数(6)* b闪避率 / 100)+32
为了好看点,我们把他变成:ahit-(blv-alv)*(6*beva/100)+32
Jeval就是用在这种情况下的!!!!

Jeval下载地址:http://www.oschina.net/p/jeval 目前最新版本是0.9.4 Beta

public class EvalTest {private static final double X_VALUE = 1.0;private static final double Y_VALUE = 270;//testJeval/testJeval2需要手動包裝變量,testJeval3增加了變量包裝方法public static void main(String[] args) throws Exception {testJeval();testJeval2();testJeval3();}private static void testJeval() throws Exception {String exp = "2 + (7-5) * 3.14159 * #{x} + sin(#{y})";// compileEvaluator eva = new Evaluator();eva.putVariable("x", Double.toString(X_VALUE));eva.putVariable("y", Double.toString(Y_VALUE));// evaluatedouble result = Double.parseDouble(eva.evaluate(exp));System.out.println(result);//-> 2.0}public static void testJeval2(){// 我们的游戏公式 ahit-(blv-alv)*(6*beva/100)+32String exp = "#{ahit}-(#{blv}-#{alv})*(6*#{beva}/100)+32";Evaluator eva = new Evaluator();try {/** * 添加变量到 Evaluator 类实例.  */eva.putVariable("ahit", "33");eva.putVariable("blv", "10");eva.putVariable("alv", "10");eva.putVariable("beva", "5");/** * 简单输出变量. *//*System.out.println(eva.evaluate("#{ahit}"));System.out.println(eva.evaluate("#{blv}"));System.out.println(eva.evaluate("#{alv}"));System.out.println(eva.evaluate("#{beva}"));*///公式计算System.out.println(eva.evaluate(exp));} catch (Exception e) {e.printStackTrace();}}public static void testJeval3(){// 我们的游戏公式 ahit-(blv-alv)*(6*beva/100)+32String exp = "ahit-(blv-alv)*(6*beva/100)+32";Evaluator eva = new Evaluator();try {/** * 添加变量到 Evaluator 类实例.  */eva.putVariable("ahit", "33");eva.putVariable("blv", "10");eva.putVariable("alv", "10");eva.putVariable("beva", "5");//公式计算System.out.println(eva.evaluate(formatExpression(exp)));} catch (Exception e) {e.printStackTrace();}}public static String formatExpression(String exp){//英文字母變量用#{ }包裝:如變量x,#{x}String re = "([a-zA-Z]+)";Pattern pattern = Pattern.compile(re);Matcher matcher = pattern.matcher(exp);StringBuffer sb = new StringBuffer();while(matcher.find()){matcher.appendReplacement(sb, "#{" + matcher.group(1) + "}");}matcher.appendTail(sb);return sb.toString();}}


0 0
原创粉丝点击