简体   繁体   中英

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:

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).

My question is:

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 ..?

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.

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". But if you mean that the b -related test evaluates to true while the others still relate to false, then the behaviour is intended. You're using a logical AND, && , to join your conditions. 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.

2) An if statement always requires a single boolean condition - which in this case you've formed from a conjunction of 150 individual conditions. If you need to inspect 150 fields to reach the overall decision, then somehow these will all need to be accessed.

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() ).

Also, if you have 150 variables, chances are they're all instances of the same sort of thing. Say, for example, you're tracking 150 files to see whether they've been generated. 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() ...)

You can do it by 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.

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