Java:错误的变量增加了吗?
问题描述:
由于某些原因,这段小小的代码无法正常工作。这是什么是应该做的是使一招,如果i
小于colLength
,这是2在这一点意味着在7键入后,应立即停止,由于某种原因它一直走,直到数组结束。Java:错误的变量增加了吗?
为什么会坚持下去?我没有任何增加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++){...
,并插入此最内层的环后(与我)
break label;
然后怎么样' for(int r = 0; r
Smit
2013-05-06 17:38:37
现在我感到很蠢。抱歉。为什么它只能两次运行呢?第4步应该只调用一次,但由于某些原因,这是唯一的一步,即使代码几乎完全相同,其他3 ... – 2013-05-06 17:41:58
我会建议您调试您的代码。我不能告诉你为什么只是看着这段代码片段。但你打印价值的块应该仔细看看。 – Smit 2013-05-06 17:50:59