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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With