java如何为二维数组生成列和行和方法?
到目前为止,我已经有了一个对列进行合计的方法,但这并不是我所需要的
我需要在每行的右边有每行的总数,在每列的底部有每列的总数。像这样的
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;
}
}
# 1 楼答案
打印矩阵后,仅为循环应用一个
取代
# 2 楼答案
您可以使用stringbuilder将每个总和附加到字符串中,然后在循环结束后将其打印出来
# 3 楼答案
打印数组后,只需在一行而不是三行中打印总数