简体   繁体   English

如何在Java中设置一系列可能的值?

[英]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. 因此,我正在编写一个Java应用程序,当输入特定范围内的值时,该应用程序将显示某些数据。 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(Number> = 5 but <= 15){将执行某些任务。 } }

If someone could help me achieve this that would be fantastic. 如果有人可以帮助我实现这一目标,那就太好了。 Regards 问候

&& is the symbol for logical and , || &&是逻辑and的符号, || is the symbol for logical or . 是逻辑or符号。 If both of your statements (Number >= 5, Number<= 15) need to be true for something to happen, you use logical and operator. 如果要使某两个语句(数字> = 5,数字<= 15)都为真,请使用逻辑and运算符。 If only one of them is needed to be true, you use logical or operator. 如果只需要其中之一为真,则使用逻辑or运算符。

In the purpose of your code, the if statement will be 就您的代码而言,if语句将是

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

I highly recommend to learn about boolean algebra. 我强烈建议您学习布尔代数。

There are 2 options. 有2个选项。 Option 1 - Same line if statement. 选项1-if语句在同一行。 This combines both conditions into the same if statement. 这将两个条件合并为相同的if语句。 it does so by combining them with an 'AND' or an "OR" statement. 它通过将它们与“ AND”或“ OR”语句结合使用来实现。 In java these are denoted as "&&" and "||" 在Java中,这些表示为“ &&”和“ ||” respectively. 分别。

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

Option 2 - 2 unique if statements. 选项2-2个唯一的if语句。 This takes the two conditions and separates them into two different if statements. 这需要两个条件,并将它们分成两个不同的if语句。 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. 您应该使用and运算符。 It enters into if loop if and only if both the condition is true. 当且仅当两个条件都为真时,它才进入if循环。 The first condition in your problem is number >=5 and second condition is. 问题中的第一个条件是数字> = 5,第二个条件是。
number <=15. 数字<= 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. 通常(Number应该大于或等于5且小于或等于15)if循环条件是:If(number> = 5 && number <= 15)And运算符:如果两个条件都成立,则进入进入if循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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