若要将数学字符串计算为int,请使用Java中的Nashorn JavaScript(即脚本)。Nashorn调用Java 7中引入的动态功能以提高性能。
要编写脚本,请对引擎使用ScriptEngineManager类:
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
现在,用于put()
在ScriptEngine的状态下设置键/值对:
scriptEngine.put("one", 10); scriptEngine.put("two", 50); scriptEngine.put("three", 40);
现在,这是数学字符串。使用eval评估:
String strExp = "(one + two - three) == 20"; Object evalExp = scriptEngine.eval(strExp);
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Demo { public static void main(String[] args) { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn"); scriptEngine.put("one", 10); scriptEngine.put("two", 50); scriptEngine.put("three", 40); try { String strExp = "(one + two - three) == 20"; Object evalExp = scriptEngine.eval(strExp); System.out.println("Is "+strExp + " ? " + evalExp); } catch (ScriptException se) { se.printStackTrace(); } } }
输出结果
Is (one + two - three) == 20 ? true