java自带解析字符串为JavaScript,可用于字符串形式的公式计算,示例如下:
public class Test {
static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
public static void main(String[] args) {
String strs = "if(S >= 12 && S < 14) {(14 - S)*1000} else if(S >= 10 && S < 12){(12 - S)*3000 + 2000}";
double result = 0;
try {
result = (double) jse.eval(strs.replace("S", "11"));
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println(result);
} catch (Exception t) {
}
}
把S=11带入公式,输出结果为:5000.0