从 CSV 中读取值时,如何将其推入二维数组?

When reading values from a CSV, how to I push into a two-dimensional array?

我有一个包含 50 行和 3 列数字的 CSV 文件。当我从文件中读取行时,我想将它们放入一个数组中并将该数组推入我的二维数组中。我该如何实现?

注意事项:

我的 CSV 文件如下所示:

(白天,高温,低温)

1,45,20
2,41,21
3,39,20
4,37,18
5,40,19
6,42,19
7,43,19
etc..

我想将每一行作为自己的数组。到目前为止,这是我的代码:

public class Temps {
  public static void main(String[] args) throws IOException {
    File fileName = new File("DaysAndTemps.csv");
    if (fileName.exists()) {
      BufferedReader br = null;
      String line = "";
      String cvsSplitBy = ",";
      br = new BufferedReader(new FileReader(fileName));
      System.out.println("----------------------------------------------------");
      System.out.println("December 2020: Temperaturs");
      System.out.println("----------------------------------------------------");
      System.out.println("----------------------------------------------------");
      System.out.println("Day " + "High " + "Low " + "Variance");
      final int rows = 50;
      final int cols = 3;
      while ((line = br.readLine()) != null) {
        String[][] matrix = new String[rows][cols];
        for (int row = 0; row < rows; row++) {
          for (int col = 0; col < cols; col++) {
            matrix[row][col] = br.readLine();
          }
        }
        System.out.println(Arrays.deepToString(matrix));
      }
    }
  }
}

这是当前的输出:

[[2,41,21, 3,39,20, 4,37,18], [5,40,19, 6,42,19, 7,43,19], [8,42,20, 9,39,19, 10,36,20], [11,35,20, 12,32,18, 13,31,16], [14,28,23, 15,35,20, 16,43,28] etc.. 

尝试一下,我可以建议一个更简单、更全面的解决方案。

只需创建一个一维数组,然后将一个易于构造的一维降级数组添加到该数组。

File fileName = new File("C:\descktop\Portfolio" +
        "\testFrorAnswers\src\com\company\res.csv");

if (fileName.exists()) {
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";
    br = new BufferedReader(new FileReader(fileName));

    System.out.println("----------------------------------------------------");
    System.out.println("December 2020: Temperaturs");
    System.out.println("----------------------------------------------------");
    System.out.println("----------------------------------------------------");
    System.out.println("Day " + "High " + "Low " + "Variance");

    final int rows = 50;
    final int cols = 3;

    while ((line = br.readLine()) != null) {
        Object[] a = new Object[50];
        for (int row = 0; row < rows; row++) {
            String[] array = br.readLine().split(",");
            a[row] = array;
        }
        System.out.println(Arrays.deepToString(a));
    }
}

结果如下

[2, 41, 21], [3, 39, 20], [4, 37, 18], [5, 40, 19], [6, 42, 19], [7, 43, 19], etc...

试一试

将您的 while 循环更改为此

String[][] matrix = new String[rows][cols];
int row = 0;
while ((line = br.readLine()) != null) {
    if (line.isEmpty()) {
        continue;
    }
    String[] items = line.split(",");
    for (int col = 0; col < cols; col++) {
        matrix[row][col] = items[col];
    }
    row++;
}