提问人:baddev 提问时间:7/7/2022 最后编辑:baddev 更新时间:7/7/2022 访问量:59
为什么我扫描文件并打印结果的方法比上次打印了 1 个空格?
Why does my method that scans a file and prints out the result print 1 space further than the last time?
问:
我目前正在编写一段相当长的代码来重新创建 Conway 的 Game of Life,并且刚刚意识到当我运行代码时,我用于扫描文件并将自身打印为矩阵的方法无法按预期工作。我试过搞砸它,但无济于事。
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;
}
当我用 调用它时,我得到System.out.println(Arrays.deepToString(originalBoardCreation()));
[[.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..., .........., ..........]]
我正在尝试得到类似的东西,但我不知道为什么会发生这种情况,所以如果我能在我的逻辑中得到一个简短的解释或错误,那就太好了,谢谢![[., x, x, x, x, x, x, x, x, .], ... etc
答:
1赞
Eric
7/7/2022
#1
我相信这个问题是由这样一个事实引起的,即您从文件中读取一行文本并期望它神奇地为您拆分为字符串数组。
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;
}
我还没有测试过这个,但这样的东西应该可以工作。
评论
line
String[]
String
inpFileName
String[] line
Char[] line
String line;
board[i][j] = line.charAt(j);
null
board[i][j]
i = 0
j = 1
line[0]
line[1]
board[0][1]