Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

Java if-statement in for-loop

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?

question from:https://stackoverflow.com/questions/65906176/java-if-statement-in-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...