我是java初学者,我正在进行for循环和while循环.我理解它们是如何工作的,但我无法弄清楚如何从for循环转换为while循环.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
for循环只是一个带有变量声明的while循环和一个在结尾执行的语句.
所以这:
for(int row=rowIndex+1; row<this.getMaxRows(); row++){
//body of the loop goes here
}
Run Code Online (Sandbox Code Playgroud)
大致相当于:
int row = rowIndex +1;
while (row < this.getMaxRows()){
//body of the loop goes here
row++;
}
Run Code Online (Sandbox Code Playgroud)
唯一真正的区别是row现在可以在while-loop 之外访问变量.如果您不想这样做,可以使用另一个块:
{
int row = rowIndex +1;
while (row < this.getMaxRows()){
//body of the loop goes here
row++;
}
}
//can't access row here.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |