AP计算机教程8-4:循环遍历二维数组的一部分
你可以仅循环二维数组的一部分。例如,可以求给定行的元素之和。
public class Test
{
public static int getTotalForRow(int row, int[][] a)
{
int total = 0;
for (int col = 0; col < a[0].length; col++)
{
total = total + a[row][col];
}
return total;
}
public static void main(String[] args)
{
int[][] matrix = {{1,2,3},{4,5,6}};
System.out.println(getTotalForRow(0,matrix));
}
}
也可以通过修改开始和结束值来循环遍历二维数组的一个矩形子区域。
public class Test
{
public static int countValues(int value, int[][] a,
int rowStart, int rowEnd,
int colStart, int colEnd)
{
int count = 0;
for (int row = rowStart; row <= rowEnd; row++)
{
for (int col = colStart; col <= colEnd; col++)
{
if (a[row][col] == value) count++;
}
}
return count;
}
public static void main(String[] args)
{
int[][] matrix = {{3,2,3},{4,3,6},{8,9,3},{10,3,3}};
System.out.println(countValues(3,matrix,0,2,0,2));
}
}
0 条评论