2014-10-19 101 views
-1

我對Java真的很陌生,對此有點麻煩。我在這裏和其他有類似問題的地方看過其他代碼,但我不明白庫文件等等。我正試圖瞭解現在的基礎知識。任何幫助,將不勝感激。我當前的代碼是:將隨機數分配給2d數組時遇到的麻煩

public static void main(String[] args) { 

     double[][] father = new double[25][25]; 
     for (int i = 0; i < 25; i++){ 
      father[i] = Math.random(); 
      for (int j = 0; j < 25; j++){ 
       father[j] = Math.random(); 
      } 

     } 
+0

太謝謝你了。我在理解編碼背後的算法時遇到了一些麻煩,這對我有很大幫助!對此,我真的非常感激。 – peneloperain 2014-10-19 05:18:14

回答

0

我不知道Java,但一個二維數組應該像這樣工作

public static void main(String[] args) { 

     double[][] father = new double[25][25]; 
     for (int i = 0; i < 25; i++){ 
      for (int j = 0; j < 25; j++){ 
       father[i][j] = Math.random(); 
      } 

     } 
0

您正在嘗試雙打的陣列設置爲雙。當試圖指定2d數組中的某個項時,請始終使用arrayName [index1] [index2]。

public static void main(String[] args) { 

    double[][] father = new double[25][25]; 
    for (int i = 0; i < 25; i++){ 
     for (int j = 0; j < 25; j++){ 
      father[i][j] = Math.random(); 
     } 

    } 
0

一個二維數組,例如你需要兩個索引來引用特定的元素。例如father[3][6]是數組的元素(雙精度型,因爲這是數組的類型),但是father[i]不是。

此外,您應該使用數組長度,而不是硬編碼值作爲迭代限制。這樣,如果數組的大小發生變化,您也不需要更改限制。您應該使用for (int i = 0; i < father.Length; i++)而不是for (int i = 0; i < 25; i++),這樣如果數組長度發生變化,您仍然可以迭代整個事物而不會溢出。

總而言之:

double[][] father = new double[25][25]; 
for (int i = 0; i < father.Length; i++) { 
    for (int j = 0; j < father[i].Length; j++) { 
     father[i][j] = Math.random(); 
    } 
}