java - 使用用户输入创建二维数组并查找特定列的总和

标签 java arrays input sum

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


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);
}

关于java - 使用用户输入创建二维数组并查找特定列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57534211/

相关文章:

jquery - 根据输入值运行函数 - jquery

javascript - 如何从 Java 编译并运行 Typescript?

c++ - 如何在 C++ 中使用构造函数(只是构造函数)初始化类中的大型私有(private)数组?

java - 仅对一个数组执行计算时,如何防止两个数组相等?

c++ - 将数组传递给没有函数的函数,因此无论如何它都不会更改原始数组

c# - 从用户输入的逗号分隔字符串中删除所有额外空格到数组中的最干净的方法是什么

c - 在 C 中获取用户的连续输入

javascript - 我怎样才能使这个动态输入字段下拉而不进入其他字段的中间

java - Spring集成-recipientlistrouter-并行处理

java - 我的 do while 循环遇到问题