Java 获取二维数组中每个单独行和列的总和
我有一行和一列的总和,但我希望分别找到每行和每列的总和。例如,输出将是第1行的总和。。第2行的总和为。。等等列也是如此Java 获取二维数组中每个单独行和列的总和,java,arrays,multidimensional-array,Java,Arrays,Multidimensional Array,我有一行和一列的总和,但我希望分别找到每行和每列的总和。例如,输出将是第1行的总和。。第2行的总和为。。等等列也是如此 public class TwoD { public static void main(String[] args) { int[][] myArray = { {7, 2, 10, 4, 3}, {14, 3, 5, 9, 16}, {99, 12, 37, 4, 2
public class TwoD {
public static void main(String[] args) {
int[][] myArray = { {7, 2, 10, 4, 3},
{14, 3, 5, 9, 16},
{99, 12, 37, 4, 2},
{8, 9, 10, 11, 12},
{13, 14, 15, 16, 17}
};
int row = 0;
int col;
int rowSum = 0;
int colSum = 0;
for(col = 0; col<5;col++)
rowSum = rowSum + myArray[row][col];
for( row = 0; row<5; row++)
System.out.println("Sum of row " + row + " is " + rowSum);
col = 0;
for(row=0; row<5;row++)
colSum = colSum + myArray[row][col];
for(col = 0; col<5; col++)
System.out.println("Sum of column " + col + " is " + colSum);
}
}
您漏了一行,请这样使用:
for(col = 0; col<5;col++) {
for( row = 0; row<5; row++) {
rowSum = rowSum + myArray[row][col];
}
System.out.println("Sum of row " + rowSum);
rowSum=0; // missed this line...
}
同样地
for(row=0; row<5;row++) {
for(col = 0; col<5; col++) {
colSum = colSum + myArray[row][col];
}
System.out.println("Sum of column " + colSum);
colSum=0;
}
为了使它更整洁,您可以通过方法将每行的总和存储在1D数组中
public static void main(String[] args)
{
int[][] table = {......}; //where ... is your array data
int[] sumOfRows = sumTableRows(table);
for ( int x = 0; x < table.length; x++ )
{
for ( int y = 0; y < table[x].length; y++ )
System.out.print( table[x][y] + "\t" );
System.out.println( "total: " + sumTableRows[x] );
}
}
public static int[] sumTableRows(int[][] table)
{
int rows = table.length;
int cols = table[0].length;
int[] sum = new int[rows];
for(int x=0; x<rows; x++)
for(int y=0; y<cols; y++)
sum[x] += table[x][y];
return sum;
}
这会输出每一行和每一列,但我得到的每一行/每一列的总和是相同的