Java Program to parse a mathematical expression and operators


At first, we have set the mathematical expressions:

String one = "10+15*20-5/5";
String two = "3+5-6";
String three = "9+2*(6-3+7)";

To parse mathematical expression, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance.

For scripting, use the ScriptEngineManager class for the engine:

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("Nashorn");

Now for JavaScript code from string, use eval i.e. execute the script. Here, we are parsing mathematical expressions set above:

Object expResult1 = scriptEngine.eval(one);
Object expResult2 = scriptEngine.eval(two);
Object expResult3 = scriptEngine.eval(three);

Example

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);
   }
}

Output

Result of expression1 = 309
Result of expression2 = 2
Result of expression3 = 29
Result of expression4 = 8
Result of expression5 = 12

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements