1

每次我调用 set() 时,它都会将数组中的所有值重置为 false,除了 int row 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++;                   
}            
4

1 回答 1

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;
     }
  }
}
于 2012-04-24T02:15:25.387 回答