I need to create a method in main to read string expression and parse it with parenthesis first.
the expression is:
(3+4)*7/2
It has to be done in java. But i don't know how to do it.
Any ideas on that!
I need to create a method in main to read string expression and parse it with parenthesis first.
the expression is:
(3+4)*7/2
It has to be done in java. But i don't know how to do it.
Any ideas on that!
Try this:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "(3+4)*7/2";
double result=0;
try {
/*
It seems that (on some platforms) this results in a java.lang.RuntimeException
because of converting Object to double, so let's replace it with
Double.doubleValue()
*/
//result = (double) (engine.eval(foo));
result = ((Double) (engine.eval(foo))).doubleValue(); //result = 24.5
} catch (ScriptException e) {
//handle exception here
}
UPDATE
Before you try to evaluate the expression, you should test if the "JavaScript" ScriptEngine is registered on your system, you can do it like this:
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
System.out.println(factory.getNames());
}
My output is
[js, rhino, JavaScript, javascript, ECMAScript, ecmascript]
If your output doesn't contain JavaScript
, then try with js
and javascript
, like
ScriptEngine engine = mgr.getEngineByName("js");
or
ScriptEngine engine = mgr.getEngineByName("javascript");
If neither of them exist you can't use js as script engine to evaluate your expression