我正在编写一个程序,以便它计算并打印数组每列的总和。给定的数据如下所示:
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
理想情况下,它应该输出结果 13, 9, 15, 13, 12, -8。但由于某些行的长度不同,当我运行程序时,它输出 13, 9, 15 并给我一个 ArrayIndexOutOfBoundsException。而且我真的不知道如何解决它。
这是我的代码:
public class ColumnSums
{
public static void main(String[] args) {
//The given data
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
//Determine the number of data in the longest row
int LongestRow = 0;
for ( int row=0; row < data.length; row++){
if ( data[row].length > LongestRow ){
LongestRow = data[row].length;
}
}
System.out.println("The longest row in the array contains " + LongestRow + " values"); //Testing
//Save each row's length into a new array (columnTotal)
int[] columnTotal = new int[4];
//Scan through the original data again
//Record each row's length into a new array (columnTotal)
System.out.println("The lengths of each row are: ");
for ( int i = 0; i < data.length; i++){
columnTotal[i] = data[i].length;
System.out.println(columnTotal[i]); //Testing
}
// Create an array to store all the sums of column
int ColumnSums[] = new int[LongestRow];
System.out.println("The sums of each column are: ");
for ( int i = 0; i < LongestRow; i++ ){
int sum = 0;
for (int j = 0; j < data.length; j++) {
sum = sum + data[j][i];
}
ColumnSums[i] = sum;
System.out.println("Column " + i + ": " + ColumnSums[i]); //Testing
}
}
}
感谢您的宝贵时间!!!
最佳答案
您基本上只需要循环遍历列,直到每行的计数器超出范围。无需提前循环查找最长的行。
public static ArrayList<Integer> getCollumnSum() {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
int col = 0;
ArrayList<Integer> totals = new ArrayList<Integer>();
while (true) {
int total = 0;
boolean dataInCol = false;
for (int i = 0; i < data.length; i++) {
if (col < data[i].length) {
total += data[i][col];
dataInCol = true;
}
}
col += 1;
if (dataInCol) {
totals.add(total);
} else {
break;
}
}
return totals;
}
输出:
[13, 9, 15, 13, 12, -8]
关于java - 如何计算二维数组中每一列的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43806382/