AP计算机教程8-3:循环二维数组
获取行数与列数
数组本身知道它们自己的长度(能储存元素的多少)。arrayName.length是一个public的只读field,可以用.来读取。外层数组的长度即是行数,而内层数组的长度即是列数(AP计算机假定所有内层数组的长度一致,因而在考试中可以使用第一个内层数组的长度作为列数)。注意到length是field而不是method,因而在之后不用加括号。
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
循环二维数组
在获得行数和列数以后,即可以用嵌套for循环(循环中有另一个循环)来遍历数组的所有元素。
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;
}
}
return total / (a.length * a[0].length);
}
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循环二维数组
因为二维数组本质上是数组的数组,你同样可以使用嵌套的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;
}
}
return total / (a.length * a[0].length);
}
public static void main(String[] args)
{
int[][] theArray = {{80, 90, 70}, {20, 80, 75}};
System.out.println(getAvg(theArray));
}
}
以上的例子中,for (int[] colArray : a)的意思是将colArray设为当前的内层数组,紧接着就能再用一次for-each遍历它了。
0 条评论