Home > Java > !Reinventing the wheel

!Reinventing the wheel

While digging into the ways I might resolve the nested bracketing of expressions I did a bit of parallel homework and discovered that javax has functionality which can be leveraged to save a world of work here, the ScriptEngine interface. I played around with it for a while and came up with this example of how we might implement a calculator using the ScriptEngine.

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

public class Evaluator {
private ScriptEngineManager sm = new ScriptEngineManager();
private ScriptEngine sEngine = sm.getEngineByName("js");

public double stringEval(String expr)
Object res = "";
        try {
           res = sEngine.eval(expr);
         catch(ScriptException se) {
        return Double.parseDouble( res.toString());


Here’s how we might use it:

Evaluator evr = new Evaluator();
String sTest = "+1+9*(2 * 5)";
double dd = evr.stringEval(sTest);

Not reinventing the wheel here proves to be a big win. It runs fast and significantly reduces the amount of code which needs to be supported. Some useful and broader based information on using scripting can be found here.


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: