2017-09-03 62 views
-1

這是我想要做的,並且出現錯誤。希望有人能指出這有什麼問題。將數組發送到某個類並從中檢索二維數組

  1. 發送陣列raw({1,2,3,4})至SelectNo類。

    public class SelectTest { 
    
        public static void main(String[] args) { 
    
        int[] raw = new int[] { 1, 2, 3, 4 }; 
    
        SelectNo select = new SelectNo(raw); 
        select.select(); 
    
        } 
    } 
    
  2. SelectNoselect()函數給出結果,束陣列,包括來自raw三個數沒有重複。所以結果必須是{1,2,3},{1,2,4},{2,3,4}。我知道如何用下面的代碼打印出結果。

public class SelectNo { 

    public int[] selected; 
    public int[] raw; 

    public SelectNo(int[] raw) { 
     this.raw = raw; 
     this.selected = new int[3]; 
    } 

    public void select() { 
     for (int i = 0; i < raw.length - 2; i++) { 
      for (int j = i + 1; j < raw.length - 1; j++) { 
       for (int k = j + 1; k < raw.length; k++) { 
        selected[0] = raw[i]; 
        selected[1] = raw[j]; 
        selected[2] = raw[k]; 
        System.out.println(selected[0]+" "+selected[1]+" "+selected[2]); 
       } 
      } 
     } 

} 
  • ,但問題是,我想保存陣列的一堆({1,2,3},{1,2, 4},{2,3,4})作爲SelectTest中的二維數組。所以我改變了select()以返回二維數組'addSelected'。我不確定select()是否合乎邏輯,因爲我得到錯誤。
  • public class SelectNo { 
    
        public int[] selected; 
        public int[] raw; 
        public int no = 0; // added 
        public int[][] addSelected; // added 
    
        public SelectNo(int[] raw) { 
         this.raw = raw; 
         this.selected = new int[3]; 
         this.addSelected = new int[no][3]; //added 
        } 
    
        public int[][] select() { //changed to return int[][] 
         for (int i = 0; i < raw.length - 2; i++) { 
          for (int j = i + 1; j < raw.length - 1; j++) { 
           for (int k = j + 1; k < raw.length; k++) { 
            selected[0] = raw[i]; 
            selected[1] = raw[j]; 
            selected[2] = raw[k]; 
            addSelected[no] = selected; //add array to 2 dimensional array 
            this.no = no + 1; 
           } 
          } 
         } return addSelected; //return 2 dimensional array 
    } 
    
    +0

    你的問題是什麼?此外,'selected'是對數組的引用,並且您將一次又一次地向addSelected添加相同的引用,這可能會導致在2D數組的每一行中都有相同的數組。 –

    +0

    @ErvinSzilagyi這篇文章在我完成句子之前已經保存。非常遺憾。我的問題是,如何將不同的數組(例如{1,2,3},{1,2,4},{2,3,4})添加到'addSelected'。 :( –

    回答

    0

    正如我在評論已經說過了,問題是,selected是數組的引用,這意味着它指向的存儲器的段,其中所述陣列的所述內容被儲存了。基本上你正在做一個淺拷貝而不是數組的深層拷貝。要糾正這一點,你可以做,而不是下面的addSelected[no] = selected;

    1. 使用for循環從selected陣列插入每一個元素中addSelected[no]
    2. 使用Arrays.copyOf()
    +0

    感謝數百萬!雖然我正嘗試使用二維數組...... :) –