gpt4 book ai didi

java - 如何在 Java 中正确读取 "maze.txt"文件

转载 作者:行者123 更新时间:2023-11-30 08:44:23 25 4
gpt4 key购买 nike

在我的家庭作业中,我们将使用递归遍历一个虚拟迷宫。我想确保我正在正确读取文件。此时我的代码的目标是读入一个包含迷宫的文本文件,并在迷宫的起点放置一个“X”。

此外,我阅读了另一篇关于将 BufferedReader 与 FileReader 结合使用的 SO 帖子,但该帖子有点含糊——这样做有什么好处?

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;
}

}
}


}

我的文本文件中的迷宫如下所示:

# # # # # # # # # # # #
# . . . # . . . . . . #
. . # . # . # # # # . #
# # # . # . . . . # . #
# . . . . # # # . # . .
# # # # . # . # . # . #
# . . # . # . # . # . #
# # . # . # . # . # . #
# . . . . . . . . # . #
# # # # # # . # # # . #
# . . . . . . # . . . #
# # # # # # # # # # # #

最佳答案

我在我的一门课上做了类似的事情,这是我在迷宫中阅读的方式,我使用了一个文件选择器,所以你应该用你的文件名替换它,然后一旦你有了迷宫,​​你就可以随心所欲地操纵它

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
# # # # # # # # # # # #
# . . . # . . . . . . #
. . # . # . # # # # . #
# # # . # . . . . # . #
# . . . . # # # . # . .
# # # # . # . # . # . #
# . . # . # . # . # . #
# # . # . # . # . # . #
# . . . . . . . . # . #
# # # # # # . # # # . #
# . . . . . . # . . . #
# # # # # # # # # # # #

关于java - 如何在 Java 中正确读取 "maze.txt"文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com