简体   繁体   中英

How to set a range of possible values in Java?

So I am programming a Java Application that shows certain data when a value between a specific range is entered. I thus far know how to use greater than or equal to and less than or equal to operators but I don't know how to use them both together.

The result I am trying to achieve is (In Simple English):

if (Number >= 5 but <= 15) { A Certain Task will be performed. }

If someone could help me achieve this that would be fantastic. Regards

&& is the symbol for logical and , || is the symbol for logical or . If both of your statements (Number >= 5, Number<= 15) need to be true for something to happen, you use logical and operator. If only one of them is needed to be true, you use logical or operator.

In the purpose of your code, the if statement will be

if (Number >= 5 && Number <= 15) {
    // task performed
}

I highly recommend to learn about boolean algebra.

There are 2 options. Option 1 - Same line if statement. This combines both conditions into the same if statement. it does so by combining them with an 'AND' or an "OR" statement. In java these are denoted as "&&" and "||" respectively.

if(number >= 5 && number <= 15) {
    //some additional logic
}

Option 2 - 2 unique if statements. This takes the two conditions and separates them into two different if statements. This is useful if you need to have logic in between the two conditions.

if(number >= 5) {
    //possible location for some extra logic before the 2nd condition
    if(number <= 15) { 
        //some logic
    }
}

You should use the and operator. It enters into if loop if and only if both the condition is true. The first condition in your problem is number >=5 and second condition is.
number <=15. In general( Number should be greater than or equal to 5 and less than or equal to 15) The if loop condition is: If(number>=5 && number <=15) And operator :If both the conditions are true then it enters into if loop.

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