简体   繁体   中英

Can you compare a variable to see if it's greater than and less than a value, without listing the variable twice?

if (age > 18 && age < 21) {
return true;
}

if (age < 18 && > 21) ???

Try this.

static boolean inrange(int age) {
    return Math.abs(age - 19.5) < 1.5;
}

public static void main(String[] args) {
    for (int i = 15; i < 25; ++i)
        System.out.println(i + " " + inrange(i));
}

output:

15 false
16 false
17 false
18 false
19 true
20 true
21 false
22 false
23 false
24 false

Or

static boolean inrange(int age) {
    switch (age) {
    case 19: case 20: return true;
    default: return false;
    }
}

No, on each side or the || is a new statement. The compiler or interpreter will not know how to parse it. For example, what happens if you want if (age > 18 && height < 5) ? The Java interpreter does not know what you want and assumes it is a mistake if the second variable is missing.

In some cases, you can use a ternary operator but this is not what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM