Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take a text file and turn it into a 2D array in Java?

Tags:

java

arrays

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

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 a 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?

like image 689
mert dökümcü Avatar asked Feb 19 '26 20:02

mert dökümcü


1 Answers

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.

It should be like,

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
    }

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

like image 135
Apurva Avatar answered Feb 21 '26 12:02

Apurva