[英]Java if-statement in for-loop
我的程序中有几个布尔值,当程序运行时,只有一个设置为 true(基于用户在控制台中的输入)。 现在我的程序有一个基本的 for 循环,如下所示: for(int i = 0; i < 5; i++){ do this}
。 但我希望“5”根据 boolean 是真的来改变。 类似if(boolean1 == true){ i < 5}else if(boolean2 == true){ i < 7}
。 如何在 java 中实现这一点,而不是为每个 boolean 编写不同的 for 循环?
假设只有两个可能的值 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
}
正如 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(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.