如果数字等于 0,则选择无限循环;如果数字大于 0,则选择循环直到某个数字 - Java

Choose to loop infinitely if a number equals 0 or loop until some number if that number is greater than 0 - Java

如果数字等于 0,我想使用 for 循环无限循环,如果数字大于 0,我想循环直到该数字。这里的代码有助于直观地理解我的意思。

    for (int i = 0; i < this.getNumRounds(); i++) {
        // 30 some lines of code
    }

    for ( ; ; ) {
        // 30 some lines of code
    }

如果getNumRounds()大于0,则执行第一个循环,如果等于0,则执行第二个。我宁愿这样做而不复制和粘贴我的 30 几行代码两次并使用 if 语句看到代码是多余的,虽然我可以使用一个函数来消除冗余,但我正在寻找是否有另一种选择。

您是否考虑过改用 while 循环?

int i = 0;
while(i < this.getNumRounds() || this.getNumRounds() == 0) {
//some 30 lines code
i++
}

所以你想要这样的东西:

int num = //whatever your number equals
if (num == 0) {
    boolean running = true;
    while (running) {
        doLoop();
    }
} else {
    for (int i = 0; i < num; i++) {
        doLoop();
    }
}

private void doLoop() {
    //some 30 lines of code
}

这段代码将循环的内容放在一个单独的方法中,并检查数字是否等于 0。如果是,程序将永远运行 doLoop() 方法。否则,它会运行直到 i 等于数字。

使用强大的三元运算符:

for (int i = 0; this.getNumRounds() == 0 ? true : i < this.getNumRounds(); i++) {
    // 30 some lines of code
}

正如 yshavit 在评论中指出的那样,有一种更简短、更清晰的表达方式:

for (int i = 0; this.getNumRounds() == 0 || i < this.getNumRounds(); i++) {
    // 30 some lines of code
}

虽然只创建一个方法并使用 if 语句会更好,但您可以在 for 循环中添加一个 if 语句以减少每次迭代的 i 。它看起来像:

for (int i = 0; i <= this.getNumRounds(); i++) {
    if(this.getNumRounds() == 0){
        i--;
    }
    // 30 some lines of code
}

注意我将 i < this.getNumRounds() 更改为 i <= this.getNumRounds。这样,如果轮数为零,则将调用循环。

您可以执行以下操作。

for (int i = 0; i < this.getNumRounds() || i == 0; ++i) {
    do {
        // 30 lines of code
    } while (this.getNumRounds() == 0);
}

如果 getNumRounds 计算起来并不简单,请考虑将其从循环中拉出并仅调用一次。