2014-03-04 98 views
-1

我想循環這個2維數組並返回第一個列表的大小。Java中的循環2維數組

例如:

double[][] array= { 
     { 15.0, 12.0}, 
     { 11.0, 16.0}, 
     { 16.0, 12.0}, 
     { 11.0, 15.0}, 
    }; 

我一起使用循環結構像內環路的線路思考....

for(int i=0; i < array.length; i++) { 
     for(int j=0; j < array.length; j++) 
     { 
      // 
     } 

    } 

任何幫助將是巨大的。謝謝。

+0

問題是什麼? – Maroun

+0

不確定Q是。爲什麼不直接檢查第一個清單呢? array [0] .length – xlm

+0

這是一個非常非常非常基本的問題。你確定你無法在Google上找到答案嗎?或者在[文檔](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/array.html)中? – avalancha

回答

2

你內心的循環還應當檢查內部陣列

for(int i=0; i < array.length; i++) { 
     for(int j=0; j < array[i].length; j++) { 
      // 
     } 
} 

的長度或使用的foreach

for(double[] row : array) { 
    for(double cell : row) { 
    // 
    } 
} 
0

爲了讓你不需要循環的第一維的大小,只是讓這

int len = array.length/// the length of the first list 

但如果你想獲得第二維的大小,並且該數組不爲空,所以得到所述第一元件的長度,如下所示:

int len = array[0].length// the length of the second one 
0

這裏的遍歷元件的2D陣列的方式:

for(double[] row : array) 
{ 
    for(double element : row) 
    { 
    // Use element here. 
    } 
} 

及其一行明智迭代。因此,如果陣列是這樣的:

double[][] array = {{1.2, 3.4}, {4.5, 5.6}}; 

然後element將在每次迭代分別具有在它1.2,3.4,4.5,5.6的值。
安全,快速,乾淨,簡潔。