这是我的代码:
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
我班上是全局变量