1

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?

0

2 Answers 2

1

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
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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(); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.