Java for 循环中的 if 语句
Java if-statement in for-loop
我的程序中有几个布尔值,当程序运行时只有一个设置为真(基于用户在控制台中的输入)。现在我的程序有一个基本的 for 循环,如下所示:for(int i = 0; i < 5; i++){ do this}
。但我希望“5”根据哪个布尔值为真而改变。类似于 if(boolean1 == true){ i < 5}else if(boolean2 == true){ i < 7}
。如何在 java 中实现这一点,而不是为每个布尔值编写不同的 for 循环?
正如 NomadMaker 所建议的,您可以使用变量作为 for 循环的边界
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(); }
假设只有两个可能的值5或7,只需执行以下操作:
int end = boolean1 ? 5 : 7;
for(int i = 0; i < end; i++){
//do this
}
为循环条件创建一个变量(例如 end
)并相应地设置值。
如果有更多变量,同样的想法适用:
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
}
我的程序中有几个布尔值,当程序运行时只有一个设置为真(基于用户在控制台中的输入)。现在我的程序有一个基本的 for 循环,如下所示:for(int i = 0; i < 5; i++){ do this}
。但我希望“5”根据哪个布尔值为真而改变。类似于 if(boolean1 == true){ i < 5}else if(boolean2 == true){ i < 7}
。如何在 java 中实现这一点,而不是为每个布尔值编写不同的 for 循环?
正如 NomadMaker 所建议的,您可以使用变量作为 for 循环的边界
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(); }
假设只有两个可能的值5或7,只需执行以下操作:
int end = boolean1 ? 5 : 7;
for(int i = 0; i < end; i++){
//do this
}
为循环条件创建一个变量(例如 end
)并相应地设置值。
如果有更多变量,同样的想法适用:
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
}