0

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!

4

1 回答 1

2

尝试这个:

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
}

更新

在尝试评估表达式之前,您应该测试“JavaScript”ScriptEngine 是否已在您的系统上注册,您可以这样做:

ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
    System.out.println(factory.getNames());
}

我的输出是

[js, rhino, JavaScript, javascript, ECMAScript, ecmascript]

如果您的输出不包含JavaScript,请尝试使用jsand javascript,例如

ScriptEngine engine = mgr.getEngineByName("js");

或者

ScriptEngine engine = mgr.getEngineByName("javascript");

如果它们都不存在,则不能使用 js 作为脚本引擎来评估表达式

于 2013-04-25T10:31:54.477 回答