//是这个意思 ?
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Script {
public static void main(String[] args) throws ScriptException {
ScriptEngine se = new ScriptEngineManager().getEngineByName("JavaScript");
//EBIT = (P-V)*Q-F
double p = 2.0;
double v = 1.0;
double q = 3;
double f = 1.2;
String expression = "EBIT = (" + p +"-" + v +")* "+ q + "-"+f;
Double value = (Double) se.eval(expression);
System.out.println(value);
}
}
追问那如果想实现传参的话怎么办呢?因为值一直都不是固定的,我试着写了一下 然而一直不对。
追答public class Script {
public static void main(String[] args) throws ScriptException {
ScriptEngine se = new ScriptEngineManager().getEngineByName("JavaScript");
//EBIT = (P-V)*Q-F
double[] t =new double[4];
Scanner scanner =new Scanner(System.in);
int i = 0;
System.out.println("输入形式:1 2 3 4 a"); // 数字以空字符隔开,以非数字结束输入
while(scanner.hasNextDouble()){
t[i++] = scanner.nextDouble();
}
scanner.close();
String expression = "EBIT = (" + t[0] +"-" + t[1] +")* "+ t[2] + "-"+t[3];
Double value = (Double) se.eval(expression);
System.out.println(value);
}
}
或者用命令行参数,或者JOptionPane.showInputDialog(),或者直接写个界面