## 获取行数与列数

```ticketInfo.length // returns the number of rows
ticketInfo[0].length // returns the number of columns```

0:00

How many rows does `a` have if it is created as follows `int[][] a = {{2, 4, 6, 8}, {1, 2, 3, 4}};`?

1

Which of the following would I use to get the value in the third row and second column from a 2D array called `nums`?

3

## 循环二维数组

```public class Test
{

public static double getAverage(int[][] a)
{
double total = 0;
int value = 0;
for (int row = 0; row < a.length; row++)
{
for (int col = 0; col < a[0].length; col++)
{
value = a[row][col];
total = total + value;
}
}
}

public static void main(String[] args)
{
int[][] matrix = {{1,2,3},{4,5,6}};
System.out.println(getAverage(matrix));
}
}```

• `total``double`类型，因而确保了结果是浮点数。如果定义为`int`的话，则无法存储平均值的小数部分。
• 行数为`a.length`
• 列数为`a[0].length`
• 循环的总次数是行数列数之积。

## 使用for-each循环二维数组

```public class Test
{

public static double getAvg(int[][] a)
{
double total = 0;
for (int[] innerArray : a)
{
for (int val : innerArray)
{
total = total + val;
}
}
}

public static void main(String[] args)
{
int[][] theArray = {{80, 90, 70}, {20, 80, 75}};
System.out.println(getAvg(theArray));
}
}```