1

この小さなコード スニペットは、何らかの理由で正しく機能していません。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
4

1 に答える 1

0

私の理解が正しければ、8 と 9 が追加された最後の 2 つの出力が間違っています。

問題は、更新された numLocation でグリッドを検索し続け、この numLocation がジェットで検索されなかったグリッドの一部にあることです。

解決策は、numLocation を見つけて変更を加えた後で、外側のループ (r と c のループ) を中断することです。

これを行うには、次の最初のラベルの前にラベルを追加する必要があります。

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

これを最も内側の for ループの後に挿入します (i を使用)

break label;
于 2014-03-26T07:00:11.450 に答える