Sunday, September 9, 2018

How do I evaluate a Mathematical Expression or Formula in Java?

You may have an expression like "1900 + 84" that you want to be evaluated, to something like "1984." You can do that easily in Java.

Make sure to import the correct packages...

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

In main(), you will need to instantiante the evaluators with...

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

And then you can use this engine by means of this...

System.out.println(engine.eval("1900+84"));

Note that this is a script-evaluator, so "100;1900+84" will result is just 1984. Additionally, you will want to cleanse any input that may be placed into engine.eval(), especially if you are working on a web-server.

No comments:

Post a Comment