Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?推荐答案一种可能的解决方案是,首先找到所有子数组的最大大小,然后重复多次以查找每一列的总和,以免获得不可用的值.One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.public static void main(String[] args) { int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50, 51, 89}, }; // Find maximum possible length of sub array int maxLength = 0; for (int i = 0; i < mat.length; i++) { if (maxLength < mat[i].length) maxLength = mat[i].length; } for (int i = 0; i < maxLength; i++) { int sum = 0; for (int j = 0; j < mat.length; j++) { // Avoid if no value available for // ith column from this subarray if (i < mat[j].length) sum += mat[j][i]; } System.out.println("Sum of Column " + i + " = " + sum); }} 这篇关于将二维数组中每一列的所有元素相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-04 07:58
查看更多