由于某些原因,这小段代码无法正常工作。如果i
小于colLength
(此时为2),这应该做的就是移动,这意味着它应在键入7后停止。由于某种原因,它会一直持续到数组末尾。
为什么继续下去?我没有增量r
的代码了吗?
//this is a 5 step process, this is the 4th
if (stepMaker == 4 && numLocation < totalSteps){
//looking through the array for the last number used in step 3, this works
for (int r = 0; r < gridRow-1; r++){
for (int c = 0; c < gridCol-1; c++){ // still looking
//using 5 instead of numLocation works, numLocation keeps going however... why?
if(grid[r][c] == (numLocation)) {
int x = 1;
for(int i = 0; i < colLength; i++){
grid[r + x][c] = numLocation + 1;
System.out.println("x=" + x + " // " +
"numLocation=" + numLocation + " // " +
"r=" + r + " // " +
"c=" + c + " // " +
"stepMaker=" + stepMaker + " // " +
"colLength=" + colLength + " // " +
"rowLength=" + rowLength);
numLocation++;
for (int xx = 0; xx < gridRow; xx++){
for (int yy = 0; yy < gridCol; yy++){
System.out.print(grid[xx][yy] + " ");
}
System.out.println("");
}
x++;
}
}
}
}
//colLength++;
stepMaker++;
}
这是输出:
x=1 // numLocation=5 // r=2 // c=2 // stepMaker=4 // colLength=2 // rowLength=3
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 5 4 3 0 0
0 0 6 1 2 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
x=2 // numLocation=6 // r=2 // c=2 // stepMaker=4 // colLength=2 // rowLength=3
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 5 4 3 0 0
0 0 6 1 2 0 0
0 0 7 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
x=1 // numLocation=7 // r=4 // c=2 // stepMaker=4 // colLength=2 // rowLength=3
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 5 4 3 0 0
0 0 6 1 2 0 0
0 0 7 0 0 0 0
0 0 8 0 0 0 0
0 0 0 0 0 0 0
x=2 // numLocation=8 // r=4 // c=2 // stepMaker=4 // colLength=2 // rowLength=3
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 5 4 3 0 0
0 0 6 1 2 0 0
0 0 7 0 0 0 0
0 0 8 0 0 0 0
0 0 9 0 0 0 0
rowLength = 3 // colLength = 2
最佳答案
如果我理解正确,则最后两个输出(其中8和9相加)是错误的。
问题是,您不断搜索带有更新的numLocation的网格,并且此numLocation位于网格的一部分中,而该部分未被搜索到。
解决方案是在找到numLocation并进行更改后中断外部循环(带有r和c的循环)。
为此,您需要在第一个标签之前添加标签:
label: for (int r = 0; r < gridRow-1; r++){...
并将其插入最里面的for循环之后(带有i)
break label;