Here is my code:
double value = 2.55;
String formule = "x+x";
and I want to replace x variable in sentence to value
variable, so my next code is:
formule = formule.replace("x", String.valueOf(value));
System.out.println(formule);
and I have 0.0+0.0
returned in terminal.
Here is my code where x -> 0.0 forever:
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;
}
Resolved!!!
i just created temporary string named tmp
and now its looks like this
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;
}
because String formule
is global variable in my class
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…