One way to evaluate simple math expressions in Java just takes a couple lines of code. It uses Javascript’s engine to do that and it is quite useful.
// to use eval
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
// to use scanner
import java.util.*;
class Main {
public static void main(String[] args)
throws Exception {
ScriptEngineManager mgr;
mgr = new ScriptEngineManager();
ScriptEngine engine;
engine = mgr.getEngineByName("JavaScript");
Scanner scan = new Scanner(System.in);
String foo = scan.nextLine();
System.out.println(engine.eval(foo));
}
}
If you want to compile and run this example, you need to have Java JDK
installed. The commands to compile and run a file called eval.java
with the
code above are:
$ javac eval.java
$ java Main
# Then you enter a math expression
# and you can see the result below
1 + 3 * 2 - 5 # input
2 # answer
That’s all for this post, thanks for reading!