1

I'm trying to define a generic Formula, e.g. "a+b" and use it to pass parameters. Any ideas how to make this thing work?

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    String Formula="a+b";

    engine.put("Formula", Formula);
    engine.put("a", "3");
    engine.put("b", "4");
    res = engine.eval("r = Formula").toString();
    System.out.println(res);

The output of the above code is "a+b" and not 7 as expected.

1

1 Answer 1

2

To bind variable names with values, use Bindings.

I thing the following code solves your question:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String formula="a+b";

Bindings bindings = engine.createBindings();
bindings.put("a", 3);
bindings.put("b", 4);

engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

Object res = engine.eval(formula);
System.out.println(res.toString());
Sign up to request clarification or add additional context in comments.

Comments

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.