2017-05-26 105 views
-2

所以我打算給一個數組列表(PolyArr)添加5個隨機數。我只是Java的初學者,不太瞭解語法。你能告訴我如何正確地格式化我的最後一行嗎?將值添加到數組列表

'package ga1; 
import java.util.*; 
import java.lang.Math; 
public class GA1 { 
    static int k=5; 
    public static void main(String[] args) { 
     double a; 
     List<Double[]> PolyArr= new ArrayList<>(k);//Creating the arraylist 
     for (int i=0; i<k; i++){ 
      a = Math.random() * 50; 
      //PolyArr.add(new Double() {a}); 
     } 
    } 
}' 
+0

https://stackoverflow.com/questions/10797034/adding-values-to-arraylist –

+0

@CharlieNg我不明白這是如何幫助! – niceman

+0

史蒂夫,你應該改變標題爲'添加陣列值數組arrays' :) – niceman

回答

0

您試圖創建一個大小爲5的數組與5隨機?使用此:

List<Double> polyArr= new ArrayList<>(k);//Creating the arraylist 
    for (int i=0; i<k; i++){ 
     double a = Math.random() * 50; // random 
     polyArr.add(a); 
    } 

注:請不要使用大寫在Java屬性,只爲類名和靜態字段

通過這種新的雙[] {A}你創建一個doulbes的陣列,大小爲1,內有1個隨機數

0

您需要首先創建數組並將其添加到數組中,然後您可以將數組添加到列表中。但是你真的需要這個陣列嗎?你不能直接添加雙重名單?

 import java.util.*; 
     import java.lang.Math; 
     public class GA1 { 
      static int k=5; 
      public static void main(String[] args) { 
       double a; 
       List<Double[]> PolyArr= new ArrayList<>(k);//Creating the arraylist 
       Double[] randNums = new Double[k]; //create the double array first based on k 
       for (int i=0; i<k; i++){ 
        randNums[i] = Math.random() * 50; // add to array    
       } 
       PolyArr.add(randNums); // then add to the list 
      } 
} 
0

PolyArr.add(new Double() {a});

的事情是你無法創建final類的子類。這是你試圖在上面做的事情。如果你在IDE中試過,你可能會注意到:

An anonymous class cannot subclass the final class Double 

我不知道這是什麼目的..可能是你正在處理。無論如何,這是很好的爲你明白髮生了什麼,你可以這樣做也:

double a[] = new double[k]; 
List<Double> PolyArr= new ArrayList<>(k);//Creating the arraylist 
for (int i=0; i<k; i++){ 
    a[i] = Math.random() * 50; 
    PolyArr.add(new Double(a[i])); 
} 

for(double i : PolyArr){ 
    System.out.println(i); 
} 

您也可以嘗試這樣的:

double a; 
List<Double[]> PolyArr= new ArrayList<>(k);//Creating the arraylist 
for (int i=0; i<k; i++){ 
    a = Math.random() * 50; 

    Double he[] = {a}; 
    PolyArr.add(he); 
} 

for(Double[] i : PolyArr){ 
    for(Double y : i) 
     System.out.println(y); 
} 

這可能不是你所期待的。然而,嘗試每一個答案。

閱讀這些:final classListArrayList Of Arrays