2015-02-23 28 views
2

我想無限循環使用for循環,如果一個數等於0,循環,直到如果數數數大於0.以下代碼可以幫助我理解所得到的結果。選擇無限循環,如果一個數等於0或循環下去,直到一些號碼,如果這個數字大於0 - Java的

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

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

如果getNumRounds()大於0,執行第一環路,如果它等於0,執行第二。我寧願這樣做,而不復制和粘貼我的30行代碼兩次,並使用if語句來查看代碼是多餘的,雖然我可以使用一個函數來取出冗餘,但我期待看看是否有另外一個選擇。

+0

我只是將30行重構爲函數並使用if-else。它會使代碼更清晰。代碼應該是自我記錄的,所以如果你對問題的描述包含一個「if-else」(如你的描述那樣),那麼把它翻譯成代碼的最清晰的方法是使用if-else。 – yshavit 2015-02-23 04:28:13

回答

2

使用強大的三元運算符:

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 
} 
+0

'a? true:b'可以完成爲'a || B'。 – yshavit 2015-02-23 04:26:32

1

你有沒有想過使用while循環呢?

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

所以,你想是這樣的:

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()方法永遠。否則,它會運行,直到我等於數字。

0

儘管它會更好,只是創建一個方法並使用if語句,您可以在for循環中添加if語句以減少每次迭代的次數。它看起來像:

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

通知我改變i < this.getNumRounds()i <= this.getNumRounds。這樣,如果回合的數量爲零,則循環將被調用。

0

你可以做到以下幾點。

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

如果getNumRounds是不平凡的計算,考慮將其拉出循環,並呼籲它只有一次。

相關問題