【问题标题】:How do I take a text file and turn it into a 2D array in Java?如何获取文本文件并将其转换为 Java 中的二维数组?
【发布时间】:2015-03-12 17:02:36
【问题描述】:

我有一个文本文件,如下:

1 1 1 0
0 0 1 0
0 0 1 0
0 9 1 0

我想阅读它并将其逐行转换为二维数组。 首先我使用了 BufferedReader 和 FileReader,然后将它们变成了一维数组。我想将我的一维数组添加到我的二维数组中。这是我的代码:

BufferedReader br = new BufferedReader (new FileReader ("num.txt"));
String line;
char[][] maze = new char[8][8];
            
while ((line = br.readLine() ) != null ){
                
    char[] row = line.toCharArray();
    int x = 0;
    for (int i = 0; i < row.length; i++) {
        maze[x][i] = row[i];
                
        System.out.print(maze[i]);
        System.out.printf("%n");
        x++;
    }
}

我正在尝试获取 2D 数组,因为稍后我将检查坐标。所以我希望我的二维数组的行由我拥有的文本文件的每一行决定。
但我得到的输出如下:

1
  
  1
    
    1
     
      0
0

  0
  
    1
    
      0
0
 
  0 

    1

      0
0

  9

    1

      0

我做错了什么?

【问题讨论】:

标签: java arrays


【解决方案1】:

你应该把System.out.printf("%n"); 放在for循环之外。 因为它在for 循环内,所以在打印每个字符后都会打印一个新行。

应该是这样的,

while ((line = br.readLine() ) != null ){

    char[] row = line.toCharArray();
        int x = 0;
        for (int i = 0; i < row.length; i++) {
        maze[x][i] = row[i];

        System.out.print(maze[i]);
        x++;
        }
        System.out.printf("%n");  //mention this
    }

还有一点,x 的增量不会影响输出的顺序

【讨论】:

    【解决方案2】:

    一个问题是您在 for 循环中递增 x,并在每次迭代 while 循环时将其值重置为 0。由于您使用此变量来计算行数,x++ 实际上属于 for 循环之外(但仍在 while 内),其初始化为 0 属于 while 循环开始之前。

    此语句System.out.printf("%n"); 也存在类似问题。您正在为 for 循环的每次迭代打印此内容,因此您在每个字符之间都有一个新行。与上面的x 相同,将此语句移到 for 循环之外(但仍在 while 内)。

         int x = 0;
         while ((line = br.readLine() ) != null )
         {
             char[] row = line.toCharArray();
             for (int i = 0; i < row.length; i++) 
             { 
                 maze[x][i] = row[i];
                 System.out.print(maze[i]);
             }
             System.out.printf("%n");
             x++;
        }
    

    【讨论】:

      【解决方案3】:
      BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
      char[][] arr = new char[4][4];
      int i,j;
      
      for (i=0; i<4; i++) {
          String[] str1=br.readLine().split(" ");
          for (j=0; j<4; j++) {
              arr[i][j] = str1[j].charAt(0);
          }
      }
      
      for (i=0; i<4; i++) {
          for (j=0; j < 4; j++) {
              System.out.print(arr[i][j]+" ");
          }
          System.out.println();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-28
        • 1970-01-01
        • 2017-10-12
        • 1970-01-01
        • 2022-07-12
        • 1970-01-01
        • 2013-05-09
        • 2016-12-20
        相关资源
        最近更新 更多