到目前为止,我有一个对列进行总计的方法,但这并不完全是我所需要的。
我需要将每行的总计放在每行的右侧,将每列的总计放在每列的底部。像这样的事情
1 2 3 4 = 10
3 4 5 6 = 18
4 6 8 10 < - Total
我现在所拥有的给出了每列的总计,但不是列下的总计。
方法
// method to add the sum of columns
public static int[] columnSum(int x[][]){
int temp[] = new int[x[0].length];
for (int i = 0; i < x[0].length; i++){
int sum = 0;
for (int j = 0; j < x.length; j++){
sum += x[j][i];
}
temp[i] = sum;
System.out.println("Index is: " + i + " Sum is: "+sum);
}
return temp;
}
}
最佳答案
This is the array
1 2 3
2 3 4
3 5 7
打印矩阵后仅再应用一个 for 循环。
System.out.println("This is the sum of the columns");
int temp[]=columnSum(firstarray);
for(int i=0;i<columns;i++)
{
System.out.print(temp[i]+"\t");
}
System.out.println();
替换为
System.out.println("This is the sum of the columns");
columnSum(firstarray);
关于java - 如何对二维数组进行列和和行和方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21891403/