2012-04-24 71 views
1

每次我調用set()它會重置數組中的所有值爲false,除了int int int col是什麼,因爲我在方法結束之前將其設置爲true。爲什麼會發生這種情況我認爲我正在複製數組B,然後將A中的值設置爲B中的值?或者我在這裏弄錯了。每次我運行這個方法我的陣列被重置

public void set(int row, int col) throws IndexOutOfBoundsException { 
    if (row >capacityr) {    
     boolean B[][] = new boolean[row+1][capacityc+1]; 
     for (int k = 0; k < capacityr; k++) 
      for (int j = 0; j < capacityc; j++) 
       B[k][j] = a[k][j];     

     capacityr=row; 
     a = B; 
    } 

    if (col >capacityc) {    
     boolean C[][] = new boolean[capacityr+1][col+1]; 
     for (int k = 0; k <capacityr; k++) 
      for (int j = 0; j < capacityc; j++) 
       C[k][j] = a[k][j];     

     capacityc=col; 
     a = C; 
    }  

    a[row][col] = true; 
    pT++;     
}    
+0

如果你想設置一個索引值,是陣列的容量之外,以真正會擴大矩陣包括指數 – Slowbro 2012-04-24 01:49:34

+0

你一定要使用本機陣列的方式。如果你使用像'ArrayList >這樣的二維'ArrayList'將會更容易,因爲它會增長以適應當前的元素數目。 – twain249 2012-04-24 02:02:27

+0

我實際上實現了另一個使用我的界面來使用Arraylist。但這對我來說是一個很大的挑戰。 – Slowbro 2012-04-24 02:08:43

回答

1

它應該更容易使用ArrayList,但我認爲這可以解決您的問題。

public void set(int row, int col) throws IndexOutOfBoundsException { 
    if(row > capacityr) { 
     if(col > capacityc) { 
     //both row and col are too big 
     boolean temp[][] = new boolean[row+1][col+1]; 

     //copy a 
     for(int i = 0; i <= capacityr; i++) { 
      for(int j = 0; j <= capacityc; j++) { 
       temp[i][j] = a[i][j]; 
      } 
     } 

     //set all the new elements to false 
     for(int i = capacityr+1; i <= row; i++) { 
      for(int j = capacityc+1; j <= col; j++) { 
       temp[i][j] = false; 
      } 
     } 

     //set row and col and a to temp 
     temp[row][col] = true; 
     a = temp; 

     //update capacity 
     capacityr = row; 
     capacityc = col; 
     } 
     else { 
     //just row is too big 
     boolean temp[][] = new boolean[row+1][capacityc+1]; 
     for(int i = 0; i <= capacityr; i++) { 
      for(int j = 0; j <= capacityc; j++) { 
       temp[i][j] = a[i][j]; 
      } 
     } 

     for(int i = capacityr+1; i <= row; i++) { 
      temp[i][capacityc] = false; 
     } 
     temp[row][col] = true; 
     a = temp; 
     capacityr = row; 
     } 
    } 
    else { 
    if(col > capacityc) { 
     //just col is too big 
     boolean temp[][] = new boolean[capacityr+1][col+1]; 
     for(int i = 0; i <= capacityr; i++) { 
      for(int j = 0; j <= capacityc; j++) { 
       temp[i][j] = a[i][j]; 
      } 
     } 

     for(int j = capacityc+1; j <= col; j++) { 
      temp[capacityr][j] = false; 
     } 
     temp[row][col] = true; 
     a = temp; 
     capacityc = col; 
    } 
    else { 
     //neither are too big 
     a[row][col] = true; 
    } 
    } 
} 
相關問題