2016-06-16 11 views
0

Ich bin Java-Anfänger und ich arbeite an einer for-Schleife und While-Schleife. Ich verstehe, wie sie funktionieren, aber ich konnte nicht herausfinden, wie man von einer for-Schleife in eine while-Schleife konvertiert.Für Schleife konvertieren While-Schleife

for(int row=rowIndex+1; row<this.getMaxRows(); row++){ 
    if(board[row][colIndex]==board[rowIndex][colIndex] && row!=rowIndex) 
    { 
     this.setBoardCell(row, colIndex, BoardCell.EMPTY); 
     score++; 
    } 
    else{ 
     break; 
    } 
} 
+1

Siehe Fragen funktionieren würde rechts -> – shoover

+0

Hier ist ein weiteres Beispiel zu verweisen: http://stackoverflow.com/questions/19917164/convert-a-for-loop-to-a-while-loop –

+0

Seltsamerweise fragte niemand zuvor, aber, warum willst du um das nochmal zu machen? –

Antwort

6

Eine for-Schleife ist nur eine while-Schleife mit einer Variablendeklaration und einer Anweisung, die am Ende ausgeführt wird.

So folgt aus:

for(int row=rowIndex+1; row<this.getMaxRows(); row++){ 
    //body of the loop goes here 
} 

entspricht in etwa folgendermaßen aus:

int row = rowIndex +1; 
while (row < this.getMaxRows()){ 

    //body of the loop goes here 

    row++; 
} 

Der einzige wirkliche Unterschied ist, dass die row Variable kann jetzt außerhalb des while -loop zugegriffen werden. Wenn Sie das tun nicht in der Lage sein wollen, können Sie einen anderen Block um zu verwenden:

{ 
    int row = rowIndex +1; 
    while (row < this.getMaxRows()){ 

     //body of the loop goes here 

     row++; 
    } 
} 
//can't access row here. 
+0

* "bekommt" ist die richtige Schreibweise. Die beiden gezeigten Schleifen sind nur annähernd äquivalent, nicht genau äquivalent. Der Bereich von 'row' in der for-Schleife ist nur die Schleife; Für die "while" -Schleife ist es der gesamte Block, in dem die Schleife sitzt. –

+0

Guter Punkt! bearbeitet. –

0

Der erste Teil einer for-Schleife die Initialisierung ist, dann ist die Kontrolle, dann die Schrittweite. Also:

int row=rowIndex+1; //first part 
while(row<this.getMaxRows())//second part { 
     if(board[row][colIndex]==board[rowIndex][colIndex] && row!=rowIndex) { 
      score++; 
     else 
      break; 
     } 
    row++;//third part 
} 
0

Ihre Frage ist unvollständig, aber laut Informationen, die Sie gegeben hat, das ist, was Sie haben sollten:

int row=rowIndex+1; 
while((board[row][colIndex]==board[rowIndex][colIndex] && row!=rowIndex)){ 
    this.setBoardCell(row, colIndex, BoardCell.EMPTY); 
    score++; 
    row++; 
} 
0

ich denke, das

while(row < this.getMaxRows()) { 
    if (board[row][colIndex] == board[rowIndex][colIndex] && row != rowIndex) { 
     this.setBoardCell(row, colIndex, BoardCell.EMPTY); 
     score++; 
     row++; 
    } 
    else { 
     break; 
    } 
}