请协助我的代码。
数组中必须有3行4列。
用户必须能够为前2列输入双打。
然后,我应该能够计算数组中每一列的总和。


public class Main {

    public static void main(String[] args)
    {
      // Implement scanner
      Scanner input = new Scanner(System.in);

      // Create loop for accepting matrix input
      // Determine row size
      System.out.println("Please enter the number 3 for the number of rows in the array:");
      int row = input.nextInt();
      //Rule for row not being 3
      while (row != 3)
      {
      System.out.println("Sorry, there must be 3 rows.");
      row = input.nextInt();
      }

      // Determine column size
      System.out.println("Please enter the number 4 for the number of columns in the array:");
      int column = input.nextInt();
      //Rule for column not being 4
      while (column != 4)
      {
      System.out.println("Sorry, there must be 4 columns.");
      column = input.nextInt();
      }

      // Declare array with row and columns the user gave
      int[][] userArray = new int[row][column];
      //Informing user how data is inputted and saved
      System.out.print("Note that the following inputs saves the numbers from left to right. So after entering 4 digits it moves onto the next row.");
      System.out.println("\n");
      for(int i=0;i < row ; i++)
      {
        for(int j=0; j< column; j++)
        {
        System.out.print("Please enter a value for the array:["+i+"]["+j+"]");
        int val = input.nextInt();
        userArray[i][j] = val;
        }
      }
      printMatrix(userArray, row, column);
    }

    public static void printMatrix(int[][] array, int row, int column)
    {
      for (int i = 0; i < row; i++)
      {
        for (int j = 0; j < column; j++)
        {
          System.out.print(array[i][j] + " ");
        }
          System.out.println();
      }
    }
}


打印输出应取决于用户输入:

1.9 2.3 5 1

5.0 7.3 6 8

2.4 3.1 3 2

第1列的总和是:9.3

第2列的总和是:12.7

第3列的总和是:14

第4列的总和是:11

最佳答案

现在,您需要按列添加数组值。它可以很简单:

private void printSumForColumn(int[][] array, int col)
{
  int sum = 0;
  for (int i = 0; i < row; i++)
  {
    sum += array[i][col];
  }
  System.out.println("The sum of column " + col + " is " + sum);
}

09-07 15:03