Question about parameters in a boolean statement

So I have this question for a Java class I am taking. It is very simple and maybe I am just missing something simple but I can’t seem to figure out how to do this:

Code and test a boolean expression that returns true if an integer variable “n” is in the range -15 to 50 inclusive but not odd in the range 10 to 20 inclusive.

The method I have been trying is this:

System.out.println(n%2==0 && n > 10 && n < 20 && n>-15 && n < 50);

While it does the non-odd number and 10-20 inclusivity correctly it will not state that a value is "true" when outside of the 10-20 range.

p.s question requires this to be done in a sout line

>Solution :

Using parentheses helps to better represent your condition, which I’ve reproduced here, annotated on what I believe to be the correct solution.

System.out.println(        // true if an integer variable “n” is 
    n >= -15 && n <= 50        // in the range -15 to 50 inclusive 
    && !(                      // but not 
        n % 2 == 1             // odd 
        && n >= 10 && n <= 20  // in the range 10 to 20 inclusive.
    )
);

note that I use >= and <=, rather than > and <, because it says "inclusive".

I don’t think it’s possible to represent this expression in a single line without using some parentheses to group some of the checks together.

Leave a Reply