是否可以在嵌套循环中添加条件循环?
Is it possible to add conditional for loop in nested ones?
在普通的嵌套for循环中,是否可以在嵌套循环中设置一个条件来判断是否运行特定的for循环?
例如,在如下代码中,当第一个循环的 int i < 3 时,是否可以跳过第二个 for 语句 (int j)?
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 3; j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
所以只有当 i < 3 时,实际执行的代码是这样的?
for(int i = 0; i < 5; i++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
之所以要这样做是因为最里面的代码很长,for循环的个数也比较长(嵌套10个左右),实在不想再重复了。我可以想到用方法来做,但是我对方法和OO编程不是很熟悉。
非常感谢,
通常,我可能会将代码提取到一个单独的方法中。但如果您不想这样做,这里有一个解决方法:
for(int i = 0; i < 5; i++) {
for(int j = 0; j < (i < 3 ? 1 : 3); j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
这样,如果i < 3
,j
循环只会执行一次。
方法方法大致如下所示:
void outer() {
for(int i = 0; i < 5; i++) {
if(i < 3) {
inner(i, 0);
} else {
for(int j = 0; j < 3; j++) {
inner(i, j);
}
}
}
}
void inner(int i, int j) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
您可能希望将方法设为静态或私有,或删除参数,或添加 return 类型等。仅凭问题中的代码很难说。
在普通的嵌套for循环中,是否可以在嵌套循环中设置一个条件来判断是否运行特定的for循环?
例如,在如下代码中,当第一个循环的 int i < 3 时,是否可以跳过第二个 for 语句 (int j)?
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 3; j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
所以只有当 i < 3 时,实际执行的代码是这样的?
for(int i = 0; i < 5; i++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
之所以要这样做是因为最里面的代码很长,for循环的个数也比较长(嵌套10个左右),实在不想再重复了。我可以想到用方法来做,但是我对方法和OO编程不是很熟悉。
非常感谢,
通常,我可能会将代码提取到一个单独的方法中。但如果您不想这样做,这里有一个解决方法:
for(int i = 0; i < 5; i++) {
for(int j = 0; j < (i < 3 ? 1 : 3); j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
这样,如果i < 3
,j
循环只会执行一次。
方法方法大致如下所示:
void outer() {
for(int i = 0; i < 5; i++) {
if(i < 3) {
inner(i, 0);
} else {
for(int j = 0; j < 3; j++) {
inner(i, j);
}
}
}
}
void inner(int i, int j) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
您可能希望将方法设为静态或私有,或删除参数,或添加 return 类型等。仅凭问题中的代码很难说。