我需要读取文本文件,然后将其中的所有字符存储到迷宫程序的2D字符数组中。我的问题是,当我尝试将它们打印出来时,它们显示为白色框。我已附上图片以便进一步说明。
名为data4-1.txt的txt文件如下,
4 5 0 0 0 0 0 0 1 0 1 1 0 1 0 1 2 0 1 0 1 0 0 1
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Testing4 {
public static void main(String args[]) {
char[][] maze = new char[100][100];
int x = 0, y = 0;
try {
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\15mik_000\\Desktop\\Text\\data4-1.txt")); //reading files in specified directory
String line;
while ((line = in .readLine()) != null) //file reading
{
String[] values = line.split(" ");
for (String str: values) {
char curr = str.charAt(0);
maze[x][y] = curr;
System.out.print(maze[x][y] + " ");
y++;
}
System.out.println("");
x++;
}
int rows = Character.getNumericValue(maze[0][0]);
int columns = Character.getNumericValue(maze[0][1]);
// System.out.println(maze[1][0]+1-1); //Gives me a box
printArray(maze, rows, columns); in .close();
} catch (IOException ioException) {}
}
public static void printArray(char[][] maze, int rows, int columns) {
for (int i = 2; i < rows + 2; i++) {
System.out.println("");
for (int j = 0; j < columns; j++)
System.out.print(maze[i][j] + " ");
}
System.out.println();
System.out.println();
}
}
答案 0 :(得分:0)
根据您的文件内容,我更喜欢Scanner
和nextInt
。我还会根据前两个maze
来确定int
的大小,我会存储int
(s)。您可以使用try-with-resources
close和Arrays.deepToString(Object[])
快速查看maze
内容。像,
String folder = "C:\\Users\\15mik_000\\Desktop\\Text";
String file = "data4-1.txt";
File f = new File(folder, file);
try (Scanner scanner = new Scanner(f)) {
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] maze = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
maze[i][j] = scanner.nextInt();
}
}
System.out.println(Arrays.deepToString(maze));
} catch (IOException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
看来你的printArray(...)
逻辑错了。
我认为它应该看起来像
public static void printArray(char[][] maze, int rows, int columns) {
int j = 0;
for (int x = 0; x < 2; x++) {
j+=2;
for (int i = 0; i < rows; i++) {
System.out.println("");
for (int k = 0; k < columns; k++)
System.out.print(maze[x][j++] + " ");
}
System.out.println();
System.out.println();
}
}
顺便说一下,这只适用于您当前填充maze
数组的方式。但是当你从文件中读取时,我看到填充maze
数组的方式存在错误。
一旦你x++
,你就不应该y=0
。如果是这样,则需要更改printArray
逻辑。
除此之外,考虑使用Scanner
按照Elliott的建议阅读文件。