0

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;
2
  • 1
    What's the problem? Commented Dec 22, 2016 at 21:21
  • clearly state your problem. Commented Dec 22, 2016 at 21:22

1 Answer 1

1

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

@jc7553a glad to help :). If the answer solved your problem consider accepting it (the tick next to the up-/downvote arrows) to mark the problem as solved ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.