Java Program to convert mathematical string to int


To evaluate mathematical string to int, 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, use put() to set a key/value pair in the state of the ScriptEngine:

scriptEngine.put("one", 10);
scriptEngine.put("two", 50);
scriptEngine.put("three", 40);

Now, here is the mathematical string. Use eval to evaluate:

String strExp = "(one + two - three) == 20";
Object evalExp = scriptEngine.eval(strExp);

Example

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

Output

Is (one + two - three) == 20 ? true

Updated on: 30-Jul-2019

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements