【问题标题】:Read from txt a 2D arraylist从 txt 读取二维数组列表
【发布时间】:2020-04-12 08:58:07
【问题描述】:

我有这个二维数组列表,我想从我的 txt 文件中读取它 使用缓冲区阅读器(Java)。有什么帮助吗?

//我的带有整数的二维数组列表 1 2 3 4 5 6 7 8 9 10 11 12

【问题讨论】:

  • 用什么语言?
  • 更多关于您使用的语言、您目前掌握的内容和格式的信息将有助于获得答案。
  • 天哪,对不起。我使用 Java,我必须阅读这个 2d 数组列表

标签: java multidimensional-array integer reader buffered


【解决方案1】:

您的输入是一维数组,因此要将其读取为二维数组 - 您必须提供(或从某处获取)结果二维数组的宽度和/或高度。

示例如下:

// Prepare memory for the output
int width=4;
int height=3;

int[][] d2 = new int[height][width];

try {
    BufferedReader br = new BufferedReader(new FileReader("test.txt"));
    String fileContent = "";
    String line;

    while ((line = br.readLine()) != null) {
      fileContent += line + " ";
    }

    String ints[] = fileContent.split("\\p{javaWhitespace}+");

    for(int i=0;i<height;i++) {
      for (int j = 0; j < width; j++) {
        if((i * width + j) >= ints.length) throw new RuntimeException("Not enough ints :-(");
        d2[i][j] = Integer.parseInt(ints[i * width + j]);
      }
    }
} catch (Exception e) {
  e.printStackTrace();
}

/// Now you have the 2d_array in d2!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2022-01-16
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多