简体   繁体   English

Java中的多个条件if()语句?

[英]Multiple conditional if() statements in Java?

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: 我知道这似乎是无法原谅的罪过,但是我有150个变量 ,并且我想创建一个执行以下操作的if函数

if(a != 0 && b != 0 && c != 0....) {
  //do this
} else {
  //do this instead
}

However , when I set one of the if statement conditions (ie 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). 但是 ,当我设置其中一个if语句条件(即b!=1 )时,而其他条件仍然相同( a!=0c!=0 )时,else函数仍在运行,即使应该初始//do this代替//do this instead (请参见上面的代码段)。

My question is: 我的问题是:

1. Is there a reason why it is not working, and if there is, how do i fix it? 1.是否有其不起作用的原因,如果存在,我该如何解决?
2. Is there a simpler way to do that without having to list all 150 variables !=0 && !=0 etc ..? 2.有没有一种更简单的方法,而不必列出所有150个变量!=0 && !=0 ..?

Cheers 干杯

Surely it would be simpler to do something like this: 这样肯定会更简单:

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
}

With an array and a loop and a boolean. 具有数组,循环和布尔值。 Review your arrays... chances are... your teacher wouldn't have you create 150 integer variables. 查看您的数组...可能是...您的老师不会让您创建150个整数变量。

int[] integers = new int[150];
integers[0] = 1; // Set your like 150 variables like this
integers[1] = 2; 

boolean isAllNotZero = false;

for(int i = 0; i < integers.length - 1; i++) {
   if(integers[i] != 0) {
     boolean isAllNotZero = true;
   }
}

if(isAllNotZero) {
  // Do something 
} else {
  // Do something else
}

1) I'm not quite sure what you mean by "set one of the if statement conditions". 1)我不太确定“设置if语句条件之一”的意思。 But if you mean that the b -related test evaluates to true while the others still relate to false, then the behaviour is intended. 但是,如果您的意思是与b相关的测试评估为true,而其他测试仍与false关联,则表明该行为是预期的。 You're using a logical AND, && , to join your conditions. 您正在使用逻辑AND和&&来加入您的条件。 Which means that the overall condition is true if and only if all of the individual conditions are true. 这意味着,当且仅当所有单个条件都为真时,总体条件才为真。

If you want the first block to be executed when any of the individual conditions is true, then you use should use an OR ( || ) instead. 如果要在任何单个条件为true时执行第一个块,则应使用OR( || )代替。

2) An if statement always requires a single boolean condition - which in this case you've formed from a conjunction of 150 individual conditions. 2) if语句始终需要一个布尔条件-在这种情况下,您是由150个独立条件的结合构成的。 If you need to inspect 150 fields to reach the overall decision, then somehow these will all need to be accessed. 如果您需要检查150个字段才能做出总体决策,那么就需要以某种方式访问这些字段。

However, you might be able to make it easier on yourself. 但是,您可能可以使自己更轻松。 For one thing, if the a and the b etc., are part of an object, then you can provide a nice public method that describes what the condition is, and hides the nasty details away (eg public boolean isReadyToExecute() ). 一方面,如果ab等是对象的一部分,则可以提供一个不错的公共方法来描述条件,并隐藏令人讨厌的细节(例如, public boolean isReadyToExecute() )。

Also, if you have 150 variables, chances are they're all instances of the same sort of thing. 另外,如果您有150个变量,则很可能它们都是同一类事物的实例。 Say, for example, you're tracking 150 files to see whether they've been generated. 例如,假设您要跟踪150个文件以查看它们是否已生成。 Instead of having variables like: 而不是像这样的变量:

private boolean fileReady1;
private boolean fileReady2;
// ...
private boolean fileReady150;

You can use an array (or some other collection) instead: 您可以改用数组(或其他集合):

private boolean[] filesReady = new boolean[150];

Now you don't have to spell out every variable by hand, in order to come up with your boolean condition: 现在,您不必手动拼出每个变量,即可得出布尔条件:

public boolean isReadyToLoad() {
   for (int i = 0; i < filesReady.length; i++) {
       if (!filesReady[i]) {
           // Found a file that wasn't ready, so we're not ready overall
           return false;
       }
   }
   // Got through all the files without finding an unready one
   return true;
}

The exact approach will depend on the nature of your problem. 确切的方法将取决于您问题的性质。 But I reckon that some combination of information hiding (ie wrapping things in nice methods) and loops will cover anything you need to do. 但是我认为, 信息隐藏 (即用好的方法包装东西)和循环的某种组合可以覆盖您需要做的所有事情。

(And don't forget that wrapping things in methods can be nested. Perhaps the first 20 fields represent one set of things, the next 30 represent another, etc. Then you could wrap each of these in a method, and implement isReadyToLoad() as something like allFilesLoaded() && status.isSignedOff() && userDao.allUsersHavePasswords() ...) (不要忘记,在方法包装的东西可以被嵌套。也许第20场代表一组东西中,未来30代表另一种,等等,那么你可以换一项中的方法,并实现isReadyToLoad()就像allFilesLoaded() && status.isSignedOff() && userDao.allUsersHavePasswords() ...)

You can do it by stream . 您可以通过stream

List<Integer> vars = new ArrayList<>();
vars.add(a);
vars.add(b);

if (vars.stream().noneMatch(v -> v == 0)) {
   // No variable = 0. Do something
} else {
   // Do something
}

It is hard to say without knowing more details about your solution. 如果不了解有关您的解决方案的更多细节,很难说。 A Karnaugh map may help you. 卡诺地图可能会对您有所帮助。

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

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