我如何采取一个文本文件,并把它变成Java中的二维数组? [英] How do I take a text file and turn it into a 2D array in Java?

查看:115
本文介绍了我如何采取一个文本文件,并把它变成Java中的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其计算方法如下:

I have a text file, it is as follows:

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

我想读这一点,并把它变成一行的二维数组行。
首先,我用的BufferedReader和的FileReader,然后把它们变成一维数组。我想补充我的一维数组被添加到我的二维数组。这里是我的code:

I want to read this and turn it into an 2D array line by line. First I used BufferedReader and FileReader, then turned them into one-dimensional arrays. I want to add my one-dimensional arrays to be added to my 2D array. Here is my code:

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

我想获得二维数组,因为我要稍后检查坐标。所以我想我的二维数组的行由文本文件我的每一行确定。结果
但输出我得到的是以下内容:

I am trying to get 2D array because I am going to check coordinates later on. So I want my 2D array's rows to be determined by every line of the text file I have.
But the output I get is the following:

1

  1

    1

      0
0

  0

    1

      0
0

  0 

    1

      0
0

  9

    1

      0

我在做什么错了?

What am I doing wrong?

推荐答案

您应该把 System.out.printf(%N); 出方for循环
因为它是循环中,它打印在打印每一个字符后的新行。

You should put System.out.printf("%n"); out side the for loop. As it's inside the for loop, it prints a new line after printing every character.

应该是这样,

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 不会影响输出的顺序

And one more thing, increment of x will not affect the sequence of output.

这篇关于我如何采取一个文本文件,并把它变成Java中的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆