Skip to content
Advertisement

Why i’m getting a error using ScriptEngineManager by passing a string formula?

I’m using Java’s ScriptEngineManager to run some math formulas that will arrive in a string value.

But I’m receiving the following error and I can’t find the reason.

    private void testFormula(){
    String form ="((15.643333435058594+15.79137191501063+15.432352762204175+15.77764736947019+15.550000190734863)/5-15)-0.6";
    String form2 = "(((13.468705654144287)^0.25)*100)–204.45040893554688";
    try {
        //Debug info
        log.info("[PRE-ENGINE][" + form + "]");

        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        form2 = engine.eval(form2).toString();

        //Debug info
        log.info("[RESULT:" + form2 + "]");

    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
}

When I run the adobe code by using the string form1 returns the result without problem. But when I use the form2 I’m getting the following error:

<eval>:1:33 Expected ; but found error   
 (((13.468705654144287)^0.25)*100)–204.45040893554688
                                 ^ in <eval> at line number 1 at column number 33

I don’t have any clue by what could be the reason of this error.

Advertisement

Answer

The main issue is that the minus sign in the String is actually the Unicode EN Dash, so it cannot be interpreted properly; replace it with the actual minus symbol (-) to fix the issue.

Another problem is that ^ is actually the bitwise XOR operator, which does not perform exponentiation. You would need to replace that with **.

console.log((((13.468705654144287)**0.25)*100)-204.45040893554688)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement