【发布时间】:2014-03-10 01:50:24
【问题描述】:
我的家庭作业要求输出锯齿状二维数组的指定列的总和。我已经看到其他解决方案展示了如何获取所有列的总和,但不是特定的列。我遇到的问题是,如果输入一列并且二维数组的一行中不存在任何元素,我会得到一个 java.lang.ArrayIndexOutOfBoundsException。
// returns sum of specified column 'col' of 2D jagged array
public static int columnSum(int[][] array, int col) {
int sum = 0;
// for loop traverses through array and adds together only items in a specified column
for (int j = 0; j < array[col].length; j++) {
sum += array[j][col];
}
return sum;
} // end columnSum()
示例:不规则数组输入(类名为 RaggedArray)
int[][] ragArray = { {1,2,3},
{4,5},
{6,7,8,9} };
System.out.println(RaggedArray.columnSum(ragArray, 2));
这显然给了我一个 ArrayIndexOutOfBoundsException,但如果要求指定列作为参数,我不知道如何修复它。有任何想法吗?感谢您提供任何帮助或建议!
【问题讨论】:
标签: arrays multidimensional-array jagged-arrays