Java字符串转成运算公式GroovyShell 实现
public static void main(String args[]) {
Binding binding = new Binding();
binding.setVariable("F",2.5);
binding.setVariable("T",30);
binding.setVariable("A",100);
binding.setVariable("P0",100);
binding.setVariable("language", "Groovy");
GroovyShell shell = new GroovyShell(binding);
Object F1 =shell.evaluate("P1=(1+0.1 * (F/100) * T)*P0; return P1 ");
Object F2 =shell.evaluate("P1=P0*(0.055*0.20+1.0011)+A; return P1 ");
System.out.println(F1);
System.out.println(F2);
}
<dependency>
<groupId&vy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.7</version>
</dependency>
ScriptEngine实现
public static void main(String args[]) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Compilable compilable = (Compilable) engine;
Bindings bindings = ateBindings(); //Local级别的Binding
String script = "(1+0.1 * (F/100) * T)*P0"; //定义函数并调⽤
CompiledScript JSFunction = null; //解析编译脚本函数
try {
JSFunction = compilablepile(script);
字符串截取公式bindings.put("F", 2.5);
bindings.put("T", 30);
bindings.put("A", 100);
bindings.put("P0", 100);
Object result = JSFunction.eval(bindings);
System.out.println(result); //调⽤缓存着的脚本函数对象,Bindings作为参数容器传⼊
} catch (ScriptException e) {
e.printStackTrace();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。