Suppose you have a String containing some mathematical operation(s). For example, we need to perform the following calculation, but for various reasons, the data type is a String: (10*(34+92)-23)/4. Rather than figuring out ways to parse it (e.g. split or some fancy regex), we can use Java’s ScriptEngine to evaluate the function as is.
Introduction
Java’s ScriptEngine has the ability to run scripts for various scripting languages, most notably JavaScript (which is what we will be using for this example). First, we create a ScriptEngineManager followed by a ScriptEngine. Next, we use our engine to evaluate a script (which can be a String, or a Reader if the script is saved as a file) using the eval method. This essentially executes the script for us.
Why?
Why would we want to do it this way? Probably because it’s more convenient and easier / quicker than using alternative methods. I want you to note that performing math is not the main function of scripting — this is just an added benefit in our specific case. We can take advantage of the ScriptEngine by passing in our String to the object and evaluating it as a script. This allows us to perform math using JavaScript without having to parse the function using more traditional (and more complicated / time consuming) methods.
The Code
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class StringEval {
public static void main(String[] args) {
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Rather than getEngineByName, you may alternatively use...
// ScriptEngine engine = manager.getEngineByExtension("js");
String math = "(10*(34+92)-23)/4";
Double result = (Double) engine.eval( math );
System.out.println( math + " = " + result.toString() );
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Conclusion
This method of evaluating a mathematical String of operations can be very useful and may save you some time if you’re trying to parse the String, instead. I can’t really say WHY you might be using a String to store your operations, but it is not entirely uncommon, especially if you’re reading user input. To read more about Java’s ScriptEngine, click here. If you know of any other useful scripting tips, let us know in the comments.
Tags: calculate, calculation, evaluate, mathematical string, ScriptEngine
