Java 程序用于解析数学表达式和运算符


首先,我们设置了数学表达式

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

更新于: 30-Jul-2019

2K+ 浏览

开启您的 职业生涯

完成课程获得认证

开始
广告