I\'m looking for a way to shorten this code up and avoid repeating code and if statements. What I\'m doing is creating a calculator that searches strings for operators &quo
There's no need of switch
statements and complex hierrachies of classes.
In order to simplify and shorten your code and calculate simple and complex expressions (represented as String
objects), you can use the Java's JavaScript API
and it's ScriptEngine
class, which basically simulates a JavaScript
console.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class MyClass{
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from String
System.out.println(engine.eval("(5+10)*2/3"));
}
}
This will output: 10.0