Java if-statement in for-loop

Viewed 150

I have a couple booleans in my program and when the program runs only one is set to true (based on the input of the user in the console). Now my program has a basic for-loop which goes as follows: for(int i = 0; i < 5; i++){ do this}. But i want the "5" to change based on which boolean is true. something like if(boolean1 == true){ i < 5}else if(boolean2 == true){ i < 7}. How can this be achieved in java instead of writing a different for loop for every boolean?

2 Answers

Assuming that there is only two possible values 5 or 7, Just do the following:

    int end = boolean1 ? 5 : 7;
    for(int i = 0; i < end; i++){ 
       //do this
    }

Create a variable (e.g., end) for loop condition and set the value accordingly.

The same idea applies if there is more variables:

    int end = 0;
    if(variable1) end = ... ; // some value 
    else if(variable2) end = ...; // some value
    ...
    else if(variableN) end = ...; // some value  

    for(int i = 0; i < end; i++){ 
       //do this
    }

Just as NomadMaker suggested, you can use a variable as the boundary of your for loop

boolean bool1;
boolean bool2;
int numberOfExecutions;

in your main function
callTheActionThatSetsOneBooleanToTrue();
if (bool1) {
    numberOfExecutions = 5;
}
if (bool2) {
    numberOfExecutions = 10;
}
for (int i=0; i < numberOfExecutions; i++) { doYourThing(); }
Related