Thursday 23 May 2019

Java: Evaluate mathematical expression given in string form


Using ‘ScriptEngineManager’ class, you can evaluate a mathematical expression given in string form.

public static Object evaluateExpression(String expression) throws ScriptException {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    return engine.eval(expression);
}

App.java
package com.sample.app;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class App {

    public static Object evaluateExpression(String expression) throws ScriptException {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        return engine.eval(expression);
    }

    public static void main(String args[]) throws ScriptException {
        Object value = evaluateExpression("2+3*7");

        System.out.println("2+3*7 = " + value);
        System.out.println("Result class : " + value.getClass());

        value = evaluateExpression("2+3*7.123");

        System.out.println("\n2+3*7.123 = " + value);
        System.out.println("Result class : " + value.getClass());
    }
}

Output
2+3*7 = 23
Result class : class java.lang.Integer

2+3*7.123 = 23.369
Result class : class java.lang.Double


You may like

No comments:

Post a Comment