请帮忙,我应该使用两种单独的方法(一种用于列,一种用于行)来总结二维数组的每个单独的行和列并将其打印出来(例如:第 1 行 = ,第 2 行= ,第 1 列 = ,第 2 列 = )。到目前为止,我有两个单独的方法,它们只能分别获取第一行和第一列,但我坚持如何在不更改返回值的情况下打印出其他行/列。这是我到目前为止所拥有的:
public class FinalSumRowColumn
{
public static void main(String[] args)
{
int[][] mat = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
System.out.println("\nSum Row 1 = " + sumRow(mat));
System.out.println("\nSum Col 1 = " + sumCol(mat));
}
public static int sumRow(int[][] mat)
{
int total = 0;
for (int column = 0; column < mat[0].length; column++)
{
total += mat[0][column];
}
return total;
}
public static int sumCol(int[][] mat)
{
int total = 0;
for (int row = 0; row < mat[0].length; row++)
{
total += mat[row][0];
}
return total;
}
}
最佳答案
为这些方法添加 row
和 col
参数,例如:
public class FinalSumRowColumn {
public static void main(String[] args) {
int[][] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("\nSum Row 1 = " + sumRow(mat, 0));
System.out.println("\nSum Col 1 = " + sumCol(mat, 0));
System.out.println("\nSum Row 1 = " + sumRow(mat, 1));
System.out.println("\nSum Col 1 = " + sumCol(mat, 1));
System.out.println("\nSum Row 1 = " + sumRow(mat, 2));
System.out.println("\nSum Col 1 = " + sumCol(mat, 2));
}
public static int sumRow(int[][] mat, int row) {
int total = 0;
for (int column = 0; column < mat[row].length; column++) {
total += mat[row][column];
}
return total;
}
public static int sumCol(int[][] mat, int col) {
int total = 0;
for (int row = 0; row < mat[0].length; row++) {
total += mat[row][col];
}
return total;
}
}
关于java - 使用两种方法添加行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197432/