-1

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

Vitalii
  • 1,137
  • 14
  • 25

1 Answers1

5

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 4
    that's a relief, I was really wondering what was wrong in the question's code! – foch Dec 12 '13 at 19:58
  • After your edit: *It looks like you must be accessing another variable (which is not initialized) named value* the variable should be initialized with a value of `0`, otherwise the code would not even compile... – Luiggi Mendoza Dec 12 '13 at 20:00
  • @LuiggiMendoza `Double value;` perhaps... who knows? – Elliott Frisch Dec 12 '13 at 20:01
  • 1
    That's variable declaration, not initialization. Local uninitialized variables cannot be used unless you set a value on them, they're not initialized with a default value like class fields. – Luiggi Mendoza Dec 12 '13 at 20:02