【发布时间】:2013-12-12 19:52:06
【问题描述】:
这是我的代码:
double value = 2.55;
String formule = "x+x";
我想将句子中的 x 变量替换为 value 变量,所以我的下一个代码是:
formule = formule.replace("x", String.valueOf(value));
System.out.println(formule);
我在终端返回了0.0+0.0。
这是我的代码,其中 x -> 0.0 永远:
protected double Formule(Double Value) throws ScriptException
{
String ValueString = Value.toString();
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Double source = null;
formule = formule.replace("sin", "Math.sin").
replace("cos", "Math.cos").
replace("tan", "Math.tan").
replace("sqrt", "Math.sqrt").
replace("sqr", "Math.pow").
replace("log", "Math.log").
replace("x", ValueString);
try {
source = (Double)engine.eval(formule);
} catch(Exception exc) {
JOptionPane.showMessageDialog(null, "Invalid input", "Error", JOptionPane.ERROR_MESSAGE);
}
this.repaint();
return source;
}
已解决!!!
我刚刚创建了名为 tmp 的临时字符串,现在它看起来像这样
protected double Formule(Double Value) throws ScriptException
{
String tmp;
tmp = formule.replace("sin", "Math.sin").
replace("cos", "Math.cos").
replace("tan", "Math.tan").
replace("sqrt", "Math.sqrt").
replace("sqr", "Math.pow").
replace("log", "Math.log").
replace("x", String.valueOf(Value));
try {
return (Double)engine.eval(tmp);
} catch(Exception fexp) {
return null;
}
return 0;
}
因为String formule 是我班级中的全局变量
【问题讨论】:
-
出了什么问题,除了明显的错字“replase”?
-
@DanielB OP 希望/需要使用基本的
String的公式评估器。这一点都没错,所以我不知道为什么这个问题会受到如此多的反对。 -
在我的代码中没有错,只是在这里,在这篇文章中
-
那你明白了一些我不明白的事情。不过我没有投反对票..
-
添加了已删除答案中的代码。下次,请编辑您的问题并添加相关信息,而不是发布答案。