2009-11-20 49 views
0

我在家庭作業中幾乎不需要任何幫助。我必須創建一個10乘10 ArrayList,而不是一個數組。這就是我所擁有的,我只需要提示如何執行for循環將日期添加到2D ArrayList。順便說一句,這是爲了把數據,是成績; 100將82(是的,我知道這是作業,但需要在正確的方向指出)2d在Java中添加數據的ArrayList

public void q6() 
{ 
    //part a 
    ArrayList<ArrayList<Double>> grades; 
    //part b 
    grades = new ArrayList<ArrayList<Double>>(10); 
    //second dimension 
    grades.add(new ArrayList<Double>(10)); 
    for(int i = 0; i < 10; i++) 
    { 
    for(int j = 0; j < 10; j++) 
    { 
     // grades.get().add(); Not sure what to do here? 
     // If this was an array I would do something like: 
     // grades[i][j] = 100 -j -i; 
    } 
    } 
} 
+0

請修正格式,如果你想讓任何人看看這個。 – bmargulies

+0

就這樣你知道我讓我的學生做了類似的事情......所以你的老師不是唯一的瘋子:-)(在我的情況下,數組的陣列將沒有任何意義!) – TofuBeer

回答

0

給定代碼,你所要做的只是改變它一點,以接收10x10矩陣。

public class Main 
{ 
    public static final int ROW_COUNT = 5; 
    public static final int COL_COUNT = 10; 

    public static void main(String[] args) 
    { 
     ArrayList<ArrayList<Double>> grades = new ArrayList<ArrayList<Double>>(); 

     for (int i = 0; i < ROW_COUNT; i++) 
     { 
     ArrayList<Double> row = new ArrayList<Double>(); 

     for (int j = 0; j < COL_COUNT; j++) 
     { 
      row.add(100.0 - j - i); 
     } 

     grades.add(row); 
     } 

     for (int i = 0; i < ROW_COUNT; i++) 
     { 
     for (int j = 0; j < COL_COUNT; j++) 
     { 
      System.out.print(grades.get(i).get(j)); 
      System.out.print(", "); 
     } 

     System.out.println(""); 
     } 
    } 
} 
1

像這樣的事情可以做?

public void q6() 
    { 
     //part a 
     ArrayList<ArrayList<Double>> grades; 
     //part b 
     grades = new ArrayList<ArrayList<Double>>(10); 
     //second dimension 
     for(int i = 0; i < 10; i++) 
     { 
      List<Double> current = new ArrayList<Double>(10); 
      grades.add(current); 

      for(int j = 0; j < 10; j++) 
      { 
       current.add(100 - j - i); 
      } 

     } 
    } 
+0

感謝您的編輯和幫助傢伙。 –

+0

感謝您的支持。我錯過了我需要在第一個for循環中創建第二個ArrayList對象。嵌套的for循環讓我不知所措。 再次感謝您的幫助。 –