Reputation: 3
Im trying to fill a 2d-array with a text file.
My text file looks like this:
#######
# .# @#
# # #
#$##$##
# # #
# #
#######
Its basicaly a level for a game. My final 2d-array shall look like this:
char [][] a = new char [6][6];
a[0][0] = #; a[0][1] = #; ... a[0][6] = #;
a[1][0] = #; a[1][1] = ; a[1][2] = . ; ... a[1][6] = #;
.
.
.
a[6][0] = #; . . . a[6][6] = #;
My attempt is to read the rows in, convert them to 1d arrays and fill the 2d array with 2 loops. Then i need to print them out.
public class pp {
public static void main (String[] args) {
char [][]array2d = new char [6][7];
In.open("Level2.txt");
while (In.done()){
for (int rows=0; rows<7; rows++){
String string = In.readLine();
char [] array1d = string.toCharArray();
for(int columns=0; columns<7;columns++){
array2d [rows][columns] = array1d [columns];
Out.print(array2d[rows][columns]);
}
Out.println();
}
}
In.close();}}
Bizarrely it only prints everything out when i set the columns to 7
char [][]a = new char [6][7];
and the rows to 6
for (int rows=0; rows<6; rows++){
I also become the error:
Exception in thread "main" java.lang.ArrayIndexOutofBoundException:0 at pp.main(pp.java:18)
thats here
array2d [rows][columns] = array1d [columns];
And i am also not able to print the array2d out (code not shown). It simply does nothing when i try to get a[6][0] for example.
Im literally searching and trying for hours, i hope you can help me.
Upvotes: 0
Views: 1181
Reputation: 331
Java 8 Streams make it really easy to create a two-dimensional character array from a text file.
char[][] array2d = Files.lines(file.toPath())
.map(String::toCharArray)
.toArray(char[][]::new);
One difference being your text file will determine the size of the two-dimensional character array.
Upvotes: 1
Reputation: 147
You can also dramatically reduce your code to not need so many for loops by realizing that when you call
In.readLine();
you are taking in a string which you correctly turn into a char array. But you could set that directly into your array. Which as the comments above have stated is not instantiated correctly. You have 7 columns and 7 rows, thus you need
new char[7][7]
But when you call say the first element counting always STARTS AT 0. So char[0][0] would output the first element
For example
public class HelloWorld
{
public static void main(String[] args)
{
char[][] x = new char[7][7];
char[] h = "Helpers".toCharArray();
x[0] = h;
for (char c : x[0]) System.out.println(c);
}
}
So in this example I set my first row in my 2D array equal to an entire list. So from here its pretty easy to find a full solution to your problem without having to use so many lines of code.
Upvotes: 0