jc7553a
jc7553a

Reputation: 3

How to convert String to math expression and evaluate using a variable?

So I know that you can use

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String infix = "3+2*(4+5)";
    System.out.println(engine.eval(infix));

which is all great but what if I wanted to evaluate a variable in that expression call it x and make that a random variable between 0 and 1. This is an idea to evaluate definite integrals using a monte carlo method by using input given by the user. So if we had something like say

    String infix = x^2+2;

Upvotes: 0

Views: 489

Answers (1)

user4668606
user4668606

Reputation:

Just use ScriptEngine#put to set the respective variable. E.g.:

...
engine.put("x", 25);
System.out.println(engine.eval("x * x + 3 * x + 5"));

Alternatively you could make use of the fact that the context of the ScriptEngine isn't switched between two eval-calls:

...
engine.eval("var x = 25");
System.out.println(engine.eval("x * x + 3 * x + 5"));

Upvotes: 1

Related Questions