!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) {
se.printStackTrace();
}
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); System.out.println(dd);
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.
Advertisement
Categories: Java
Java, String Manipulation, String Math, String to Math