DodoProgramms DodoProgramms - 5 months ago 9
Java Question

Java - Multiple Boolean Conditions

I have this problem: I want to check if an int is bigger than 10, if not than if he is bigger then 100..and so on.
Is there a better way than just doing this:

public void multipleIf(int x){
if(x > 10){
...
} else if(x > 100){
...
} else if(...
}


Thanks.

Answer

A number that is greater than 100 is always greater than 10.

If you want only numbers in the range 10-100 exclusive, you can use operators. You could test for a number that is greater than 10 but less than 100 by using logical operators:

if(x > 10 && x < 100) {
    /* Body */
} else if(x > 100 && x < ....) {
    /* Body */
} 

The && is a logical AND operator that checks if both conditions are true. So, it checks if x is inside the range, exclusive.

If you want only numbers greater than 100, use separate if statements.

You can also use a switch statement.