Java:错误的变量增加了吗?

时间:2013-05-06 17:33:05

标签: java variables if-statement for-loop increment

由于某种原因,这段代码片段无法正常工作。这应该做的是在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

1 个答案:

答案 0 :(得分:0)

如果我理解正确的话,最后两个输出,其中添加了8和9是错误的。

问题是,你继续用更新的numLocation搜索网格,这个numLocation位于网格的一部分,没有搜索到。

解决方案是在找到numLocation并进行更改后打破外部循环(带有r和c的循环)。

为此,您需要在第一个之前添加标签:

label: for (int r = 0; r < gridRow-1; r++){...

并在最里面的for循环(使用i)之后插入

break label;