Java Algorithms How to - Parse a mathematical expression and operators and solve it








Question

We would like to know how to parse a mathematical expression and operators and solve it.

Answer

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
//w ww  .  j  a v a2s .co m
public class Main {
  public static void main(String[] args) throws Exception {
    String xyz = "3*3+3";
    String kkk = "(100 % 6)* 7";
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine se = manager.getEngineByName("JavaScript");
    Object result1 = se.eval(xyz);
    Object result2 = se.eval(kkk);
    System.out.println("result1: " + result1);
    System.out.println("result2: " + result2);
  }
}

The code above generates the following result.