问题描述
我知道这似乎是一种不可原谅的罪,但我有 150个变量,我想创建一个 if function 来执行以下操作:
I know this is going to seem like an unforgiveable sin, but I have 150 variables, and I want to create an if function that does the following:
if(a != 0 && b != 0 && c != 0....) {
//do this
} else {
//do this instead
}
然而,当我设置一个if语句条件(即 b!= 1
)时,其他仍然是相同的( a!= 0
, c!= 0
),else函数仍在运行,甚至虽然它应该是最初的 //这个
而不是 //这样做
(参见上面的代码片段) 。
However, when I set one of the if statement conditions (i.e b!=1
), whilst the others are still the same (a!=0
, c!=0
), the else function is still run, even though it should be the initial //do this
instead of the //do this instead
(see code snippet above).
我的问题是:
1。这是有原因的吗?不工作,如果有,我该如何解决?
2。有没有更简单的方法可以做到这一点而无需列出所有150个变量!= 0&& != 0
etc ..?
1. Is there a reason why it is not working, and if there is, how do i fix it?
2. Is there a simpler way to do that without having to list all 150 variables !=0 && !=0
etc..?
干杯
推荐答案
当然这样做会更简单:
List<Integer> values = new ArrayList<Integer>();
values.add(val1);
values.add(val2);
// And so forth...
boolean pass = true;
for (Integer v : values) {
if (v != 0) {
pass = false;
// You could log which variable failed here...
}
}
if (pass) {
// Do something
} else {
// Do something else
}
这篇关于Java中的多个条件if()语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!