Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

java - Evaluate math formula from String using ScriptEngine

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...