Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

This code (from your post) -

public static void main(String[] args) {
  double value = 2.55;
  String formule = "x+x";
  formule = formule.replace("x",
      String.valueOf(value));
  System.out.println(formule);
}

prints

2.55+2.55

when run here. Are you sure you're accessing the same double value you initialized above? It looks like you must be accessing another variable (which is not initialized as expected - so has the value 0) named value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...