Java程序解析数学表达式和运算符
首先,我们设置了数学表达式:
String one = "10+15*20-5/5"; String two = "3+5-6"; String three = "9+2*(6-3+7)";
要解析数学表达式,请在Java中使用NashornJavaScript(即脚本)。Nashorn调用Java7中引入的动态功能以提高性能。
要编写脚本,请对引擎使用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
热门推荐
10 朋友领证祝福语长文简短
11 周末愉快祝福语高级简短
12 水晶婚夫妻祝福语简短
13 老公生日祝福语简短好看
14 开业经典祝福语简短
15 亲姐姐怀孕祝福语简短
16 生日油画棒祝福语简短
17 前程祝福语简短暖心
18 生日祝福语简短独特格式