检查是否一个变量从一个给定的任何值
-
20-09-2019 - |
题
我
如何,如果一个条件通过多个值检查?
示例:
if(number == 1,2,3)
我知道逗号不起作用。
解决方案
if (number == 1 || number == 2 || number == 3)
其他提示
如果你正在使用PHP,那么假设你的号码列表是一个数组
$list = array(1,3,5,7,9);
那么对于任意的元件,可以使用
if(in_array($element, $list)){
//Element present in list
}else{
//not present.
}
功能结构:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
希望有所帮助。
if ((number >= 1) && (number <= 3))
什么语言?
例如在VB.NET使用字OR,并在C#使用||
由于你没有指定语言,我加一个Python的解决方案:
if number in [1, 2, 3]:
pass
在T-SQL可以使用IN操作符:
select * from MyTable where ID in (1,2,3)
如果您使用的是收集有可能是一个包含了运营商的另一种方式来做到这一点。
在C#为另一种方式可以更容易地添加值:
List<int> numbers = new List<int>(){1,2,3};
if (numbers.Contains(number))
我假设C风格的语言,这里的一对IF,AND,OR逻辑快速入门:
if(variable == value){
//does something if variable is equal to value
}
if(!variable == value){
//does something if variable is NOT equal to value
}
if(variable1 == value1 && variable2 == value2){
//does something if variable1 is equal to value1 AND variable2 is equal to value2
}
if(variable1 == value1 || variable2 = value2){
//does something if variable1 is equal to value1 OR variable2 is equal to value2
}
if((variable1 == value1 && variable2 = value2) || variable3 == value3){
//does something if:
// variable1 is equal to value1 AND variable2 is equal to value2
// OR variable3 equals value3 (regardless of variable1 and variable2 values)
}
if(!(variable1 == value1 && variable2 = value2) || variable3 == value3){
//does something if:
// variable1 is NOT equal to value1 AND variable2 is NOT equal to value2
// OR variable3 equals value3 (regardless of variable1 and variable2 values)
}
所以,你可以看到你可以连这些检查,共同创造一些非常复杂的逻辑。
有关整数列表:
static bool Found(List<int> arr, int val)
{
int result = default(int);
if (result == val)
result++;
result = arr.FindIndex(delegate(int myVal)
{
return (myVal == val);
});
return (result > -1);
}
在Java中,你有一个包裹原始变量的对象(整数对于int,龙长等)。如果你看到了很多完整的数字(整数)之间的比较值,你可以做的是启动了一堆整数对象,他们的东西的,例如迭代内的一个ArrayList,在它们之间迭代和比较。
是这样的:
ArrayList<Integer> integers = new ArrayList<>();
integers.add(13);
integers.add(14);
integers.add(15);
integers.add(16);
int compareTo = 17;
boolean flag = false;
for (Integer in: integers) {
if (compareTo==in) {
// do stuff
}
}
当然少数值,这可能是一个有点笨拙,但如果你想进行比较的很多价值观,它会很好地工作。
另一种选择是用java 设置一>,您可以将很多不同的值(集合将整理您的输入,这是一个加号),然后调用.contains(Object)
方法来定位平等。
不隶属于 StackOverflow