문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

Turning my comment to an anwser

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

No it is actually producing the correct result. Your expression is evaluated like this:

  1. 2 < x => true
  2. true < 5 => 1 < 5 (type coercion)
  3. 1 < 5 => true
  4. true

To work around try specifying that both conditions must be met.

System.out.println((Boolean) engine.eval("2 < x && x < 5"));

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top