Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect Answers when evaluating a String

My code looks like this:

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    int x = 10;
    engine.eval("x =" + x);
    System.out.println((Boolean) engine.eval("x < 5"));
    System.out.println((Boolean) engine.eval("2 < x < 5"));

The first SOP prints false as expected, but the second SOP prints true. It doesn't give correct results when I compare the variable with two values. It gives true, even if half of the condition is true. Any workaround for this? Please suggest. Thanks.

like image 963
Venkateshwarrao Surabhi Avatar asked Jul 21 '26 17:07

Venkateshwarrao Surabhi


2 Answers

2 < x < 5 doesn't do what you think it does. It's evaluated as follows:

2 < x < 5
(2 < x) < 5
(2 < 10) < 5
true < 5
1 < 5
true

Try (2 < x) && (x < 5) instead.

like image 94
Oliver Charlesworth Avatar answered Jul 23 '26 06:07

Oliver Charlesworth


Turning my comment to an anwser

2 < x < 5 => (2 < 10 ) < 5 => (true) < 5 => 1 < 5 => true

like image 24
GETah Avatar answered Jul 23 '26 07:07

GETah