首先,我们设置了数学表达式:
String one = "10+15*20-5/5"; String two = "3+5-6"; String three = "9+2*(6-3+7)";
要解析数学表达式,请在Java中使用Nashorn JavaScript(即脚本)。Nashorn调用Java 7中引入的动态功能以提高性能。
要编写脚本,请对引擎使用ScriptEngineManager类:
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("Nashorn");现在,对于来自字符串的JavaScript代码,请使用eval即执行脚本。在这里,我们正在解析上面设置的数学表达式:
Object expResult1 = scriptEngine.eval(one); Object expResult2 = scriptEngine.eval(two); Object expResult3 = scriptEngine.eval(three);
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Demo {
public static void main(String[] args) throws Exception {
String one = "10+15*20-5/5";
String two = "3+5-6";
String three = "9+2*(6-3+7)";
String four = "(10 % 3)*2+6";
String five = "3*3+3";
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("Nashorn");
Object expResult1 = scriptEngine.eval(one);
Object expResult2 = scriptEngine.eval(two);
Object expResult3 = scriptEngine.eval(three);
Object expResult4 = scriptEngine.eval(four);
Object expResult5 = scriptEngine.eval(five);
System.out.println("Result of expression1 = " + expResult1);
System.out.println("Result of expression2 = " + expResult2);
System.out.println("Result of expression3 = " + expResult3);
System.out.println("Result of expression4 = " + expResult4);
System.out.println("Result of expression5 = " + expResult5);
}
}输出结果
Result of expression1 = 309 Result of expression2 = 2 Result of expression3 = 29 Result of expression4 = 8 Result of expression5 = 12