2013-05-06 75 views
1

由於某些原因,這段小小的代碼無法正常工作。這是什麼是應該做的是使一招,如果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 
+0

然後怎麼樣' for(int r = 0; r Smit 2013-05-06 17:38:37

+0

現在我感到很蠢。抱歉。爲什麼它只能兩次運行呢?第4步應該只調用一次,但由於某些原因,這是唯一的一步,即使代碼幾乎完全相同,其他3 ... – 2013-05-06 17:41:58

+0

我會建議您調試您的代碼。我不能告訴你爲什麼只是看着這段代碼片段。但你打印價值的塊應該仔細看看。 – Smit 2013-05-06 17:50:59

回答

0

如果我理解正確的話,最後的兩個輸出,其中增加8和9都是錯誤的。

問題是,你繼續搜索網格與更新的numLocation和這個numLocation是在網格的一部分,這是沒有搜索噴氣。

解決方法是在找到numLocation並進行更改後,打破外部循環(帶有r和c的循環)。

要做到這一點,你需要之前第一個爲添加一個標籤:

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

,並插入此最內層的環後(與我)

break label;