I'm currently writing a quite lengthy piece of code to recreate Conway's Game of Life and have just realized that when I run my code, the method that I made to scan through a file and print itself out as matrix doesn't work as intended. I've tried messing around with it, but to no avail.
public static String[][] originalBoardCreation() {
Scanner sc= MyUtils.readFile(inpFileName);
width = sc.nextInt();
height = sc.nextInt();
sc.nextLine();
String[][] board = new String[width][height];
String[] line = new String[board.length];
while (sc.hasNext()) {
for (int i = 0; i < board.length; i ) {
line[i] = sc.nextLine().trim();
for (int j = 0; j < line.length; j ) {
board[i][j] = line[j];
}
}
}
return board;
}
When I call it to main with System.out.println(Arrays.deepToString(originalBoardCreation()));
, I get
[[.xxxxxxxx., null, null, null, null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., null, null, null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., null, null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., null, null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., null, null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., null, null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., null, null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., ....xxx..., null, null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., ....xxx..., .........., null], [.xxxxxxxx., x.x.x.x.x., .x.x.x.x.., xxxxxxx..., .........., .........., .........., ....xxx..., .........., ..........]]
I'm trying to get something like [[., x, x, x, x, x, x, x, x, .], ... etc
, but I have no clue as to why this is happening, so it would be great if I could get a brief explanation or error in my logic, thank you!
CodePudding user response:
I believe the problem is being caused by the fact that your reading a line of text from a file in and expecting it to be magically split for you into a string array.
public static String[][] originalBoardCreation()
{
Scanner sc= MyUtils.readFile(inpFileName);
width = sc.nextInt();
height = sc.nextInt();
sc.nextLine();
String[][] board = new String[width][height];
while ( sc.hasNext() )
{
for ( int i = 0; i < board.length; i )
{
String line = sc.nextLine().trim(); // read the text line in
char tiles[] = line.toCharArray(); // now split the line into an array
for ( int j = 0; j < tiles.length; j )
{
board[i][j] = String.valueOf(tiles[j]); // Now assign the elements to the current row on your board
}
}
}
return board;
}
I haven't tested this, but something like this should work.