在二维数组中添加列

时间:2019-03-22 18:01:32

标签: java

我需要知道如何创建一个循环,以便程序计算4列中的第一个数字

我想算出第1列中的第一个数字

        Scanner in = new Scanner(System.in);

    double[][] m = new double[3][4];

    System.out.println("Enter " + m.length + "-by-" + m[0].length + " matrix row by row: ");
    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m[0].length; j++) {
            m[i][j] = in.nextDouble();
        }
    }

    for (int j = 0; j < m[0].length; j++) {
        System.out.printf("Sum of the elements at column %d is %.1f%n", j, sumColumn(m, j));
    }
}

public static double sumColumn(double[][] m, int columnIndex) {
    double sum = 0.0;
    for (int i = 0; i < m.length; i++) {
        sum += m[i][columnIndex];
    }
    return sum;
}

} 我希望程序能计算出4列中的第一个数字

2 个答案:

答案 0 :(得分:0)

看起来您正在终止for循环,并且缺少括号。

理想情况下,您可能想要一个类似于以下的循环:

for (int col = 0; col < matrix[0].length; col++) {
    for (int row = 0; row < matrix.length; row++) {
        matrix[row][col] = scanner.nextDouble();
    }
}

答案 1 :(得分:0)

尝试在括号中添加for循环块:

import java.util.Arrays;

class TwoDMatrixColSumExample {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int rows = 3, cols = 4;
    double[][] matrix = new double[rows][cols];
    System.out.println("Please enter the values for the " + rows + " rows and " + cols + " columns.");
    for (int row = 0; row < matrix.length; row++) {
      for (int col = 0; col < matrix[0].length; col++) {
        System.out.print("Row " + row + ", Column " + col + ": ");
        matrix[row][col] = scanner.nextDouble();
      }
    }
    scanner.close();
    System.out.println("You entered: " + Arrays.deepToString(matrix));
    System.out.println("Sum of column 1 is: " + sumColumn(matrix, 1));
  }

  private static Double sumColumn(double[][] matrix, int col) {
    if (col < 0 || col >= matrix[0].length) {
      return null;
    }
    double sum = 0.0;
    for (int row = 0; row < matrix.length; row++) {
      sum += matrix[row][col];
    }
    return sum;
  }
}

用法示例:

Please enter the values for the 3 rows and 4 columns.
Row 0, Column 0: 0
Row 0, Column 1: 1
Row 0, Column 2: 0
Row 0, Column 3: 0
Row 1, Column 0: 0
Row 1, Column 1: 1
Row 1, Column 2: 0
Row 1, Column 3: 0
Row 2, Column 0: 0
Row 2, Column 1: 1
Row 2, Column 2: 0
Row 2, Column 3: 0
You entered: [[0.0, 1.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]
Sum of column 1 is: 3.0