下面的代码对String rani=String rani= "32*0.25";并给出正确的输出为8.0
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class StringMathEngine {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String rani = "32*0.25";
System.out.println(engine.eval(rani));
}
}
但是在以下代码中使用时失败:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class StringMathEngine {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String[]rani = {"s", "32*0.25", "r", "32*0.75+16", "r", "16", "s", "32"};
for(int n=0;n<rani.length; n++){
if(rani[n].equals("s")) {
rani[n]=rani[n].replaceAll("s","C/");
}
else if(rani[n].equals("r")){
rani[n]=rani[n].replaceAll("r","D/");
}
else {
rani[n]=engine.eval(rani[n]);
}
System.out.println(rani[n]);
}
}
}
作为编程新手,我需要帮助来纠正这段代码。
(最初缺少分号)
问题是ScriptEngine.eval(...)
返回一个Object
,还有一个System.out.println(Object)
。然而,将对象赋值给String
会产生一个适当的错误。
for (int n=0; n < rani.length; n++) {
if (rani[n].equals("s")) {
rani[n] = rani[n].replace("s","C/");
} else if(rani[n].equals("r")) { // ('else' missing)
rani[n] = rani[n].replace("r","D/");
} else {
rani[n] = engine.eval(rani[n]); // Semicolon missing!
try {
rani[n] = String.valueOf(engine.eval(rani[n]));
} catch (ScriptException e) {
e.printStackTrace(System.out);
}
}
System.out.println(rani[n]);
}
或者你可以使用变量:
engine.put("s", "C/");
engine.put("r", "D/");