Eval Implementation in Java

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ExprCompute {
    public double getDoubleValue(String exprStr)  {
        Double result = null;

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        try {
            result = (Double)engine.eval(exprStr);
        } catch (ScriptException ex) {
            Logger.getLogger(ExprCompute.class.getName()).log(Level.SEVERE, null, ex);
        }

        return result;
    }

    public Integer getIntegerValue(String exprStr)  {
        Integer result = null;

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        try {
            double doubleVal = (Double)engine.eval(exprStr);
            result = (int)doubleVal;
        } catch (ScriptException ex) {
            Logger.getLogger(ExprCompute.class.getName()).log(Level.SEVERE, null, ex);
        }

        return result;
    }
}
class Main {
    public static void main(String[] args)  {
        String expr1 = "5 + 6";
        String expr2 = "2.5 * 3.4";

        ExprCompute exprCompute = new ExprCompute();
        System.out.println("Result of " + expr1 + " is " + exprCompute.getIntegerValue(expr1));
        System.out.println("Result of " + expr2 + " is " + exprCompute.getDoubleValue(expr2));
    }
}

source

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: