2016-03-11 47 views
0
public class MultiDimen { 
    public static void main(String[] arg) { 
     int firstArray[][] = { { 8, 9, 19, 11 }, { 12, 13, 14, 15 }, }; 
     int secondArray[][] = { { 30, 31, 32, 33 }, { 43 }, { 4, 5, 6, }, }; 
     System.out.println("This is the first Array"); 
     display(firstArray); 
     System.out.println("This is the second Array"); 
     display(secondArray); 

    } 

    public static void display(int x[][]) { 
     for (int row = 0; row < x.length; row++) { 

      System.out.println("ROW:" + x[row].length + "[row].length"); 

      for (int column = 0; column < x[row].length; column++) { 

       System.out.print(x[row][column] + "\t"); 
      } 
      System.out.println(); 
     } 
    } 
} 

我明白这里发生了什么,但是,有一点不清楚的是x [row] .length的作用是什么? 我知道x.length获得传入的colomns x数组的长度。但row不是一个数组,它被声明为int,所以我们为什么要这样做?x [row] .length做什么?

+1

,因为它是它报告X [行]的阵列长度的二维阵列 –

+0

'length'是内置的Java中的数组的属性。它用于确定任何数组的大小。 – Keerthivasan

回答

2

一个例子,使用自己的代码,将最好的解释x[row].length是这样做的:

int secondArray[][]={ 
     {30,31,32,33}, 
     {43}, 
     {4,5,6,}, 
}; 

for (int row=0; row < secondArray.length; ++row) { 
    System.out.println("Row " + (row+1) + " has " + secondArray[row].length + " elements."); 
} 

row[i].length产生包含在你的2D int[][]的第i个位置的1D int[]数组中元素的个数阵列。

输出:

Row 1 has 4 elements. 
Row 2 has 1 elements. 
Row 3 has 3 elements. 
+0

非常明确的例子。 – Keerthivasan

0
int numOfRows = matrix.length; 
int numOfCols = matrix[0].length; 
相关问题