对于我的家庭作业,我们将使用递归遍历虚拟迷宫。我想确保我正确地阅读文件。此时我的代码的目标是读入包含迷宫的文本文件,并在迷宫的起始点放置一个“X”。
此外,我在另一篇SO帖子中读到了关于将BufferedReader与FileReader一起使用的帖子,但帖子有点模糊 - 这有什么好处?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadInMaze
{
private static char[][] maze = null;
private static int rows = 0;
private static int cols = 0;
private static int xStart = 0;
private static int yStart = 0;
public static void Maze(File mazeFile) throws IOException
{
File mazeFile = new File ("C:/Users/Mark/workspace/18-20_MazeTraversal_Hard/src/MazeForMazeTraversalHW.txt");
BufferedReader reader = new BufferedReader(new FileReader(mazeFile));
Scanner lineOfFile = new Scanner(reader.readLine());
rows = lineOfFile.nextInt(); //get the number of rows of the maze
cols = lineOfFile.nextInt(); // get the number of columns of the maze
maze = new char[rows][cols]; //create a char array of the proper size
//For loops to iterate the rows and col to find the start/enterance of the maze as it pertains to the first char in the row
for (int y = 0; y < cols; y ++)
{
lineOfFile = new Scanner(reader.readLine());
for(int x = 0; x < rows; x++)
{
char start = lineOfFile.next().charAt(0);
maze[x][y] = start;
//statement to set the starting coorinates for the maze
if (start == '.')
{
xStart = x;
yStart = y;
}
}
}
}
我的文本文件中的迷宫如下所示:
# # # # # # # # # # # #
# . . . # . . . . . . #
. . # . # . # # # # . #
# # # . # . . . . # . #
# . . . . # # # . # . .
# # # # . # . # . # . #
# . . # . # . # . # . #
# # . # . # . # . # . #
# . . . . . . . . # . #
# # # # # # . # # # . #
# . . . . . . # . . . #
# # # # # # # # # # # #
答案 0 :(得分:2)
我为我的一个课程做了类似的事情,这是我在迷宫中读到的,我使用了一个文件追踪器,所以你应该用你的文件名替换它,然后一旦你有了迷宫,你可以随意操纵它< / p>
BufferedReader read = new BufferedReader(new FileReader(chooser.getSelectedFile()));
String rea = read.readLine();
String[] split = rea.split(" ");
width = Integer.valueOf(split[0]);
height = Integer.valueOf(split[1]);
String readline;
int num = 0;
maze1 = new char[width][height];
while((readline = read.readLine()) != null){
char[] ch = readline.toCharArray();
for(int i = 0;i < ch.length;i++){
maze1[i][num] = ch[i];
}
num++;
}
假设你的迷宫的格式是这样的,迷宫文件顶部的宽度和高度用空格隔开
12 12
# # # # # # # # # # # #
# . . . # . . . . . . #
. . # . # . # # # # . #
# # # . # . . . . # . #
# . . . . # # # . # . .
# # # # . # . # . # . #
# . . # . # . # . # . #
# # . # . # . # . # . #
# . . . . . . . . # . #
# # # # # # . # # # . #
# . . . . . . # . . . #
# # # # # # # # # # # #