读取由字符组成的迷宫文件,并写入数组(java)

Reading a maze file composed of characters, and write to an array (java)

我有一个程序试图从文件中读取字符并将它们输入到数组中。我仍在尝试掌握 java 中的数组。

    // Read the file describing the maze.
static void readMazeFile(String mazefile) throws FileNotFoundException {
    File themaze = new File(mazefile);
    Scanner text_reader = new Scanner(themaze);
    int height = text_reader.nextInt();
    int width = text_reader.nextInt();
    char[][] amaze = new char[((2 * height) + 1)][];
    for (int r = 0; r < height; r++) {
        for (int c = 0; c < width; c++) {
            char pos = text_reader.next().charAt(0);
            System.out.print(pos);
            amaze[r][c] = pos;

        }

    }

}

// Solve the maze.
static boolean solveMaze() {
    return true;
}
}

这是我目前正在使用的代码,输入效果很好,所以我不相信它是这样的,因为我花了很多时间让它工作。我试图让两个 for 循环脱离 Stack Overflow,但我的问题似乎来自 amaze[r][c] = pos;线。

+Exception in thread "main" java.lang.NullPointerException
    at MazeSolver.readMazeFile(MazeSolver.java:81)
    at MazeSolver.main(MazeSolver.java:29)

是我得到的错误。老实说,我被困住了,不知道从这里去哪里。文本文件如下所示:

2 3
+-+-+-+
|S|   |
+ + + +
|   |E|
+-+-+-+

它完美地读取了前两行,所以这些都得到了处理。我只需要帮助让循环读取每一行,并在全部读取后更改行。我需要记住的一件事是我们有 6 个迷宫,并不是所有的都是完美的 squares/rectangles 例如我给出的那个。

如果方向正确,那就太棒了,谢谢大家。

主要()代码:

    public static void main(String[] args) throws FileNotFoundException {
    if (handleArguments(args)) {
        mazefile = args[0];

        readMazeFile(mazefile);
        char[][] maze = new char[3][];
        maze[0] = new char[] { '+', '-', '+' };
        maze[1] = new char[] { '|', 'S', '|' };
        maze[2] = new char[] { '+', '-', '+' };
        DrawMaze.draw(height, width, maze, borderwidth, cellsize, sleeptime);

        if (solveMaze())
            System.out.println("Solved!");
        else
            System.out.println("Maze has no solution.");
    }
}

我认为,问题是缺少第二维尺寸。

第一种方式

//static declaration 

char[][] amaze = new char[((2 * height) + 1)][1];

第二种方式

//dynamic decalaration of second dimension

char[][] amaze = new char[((2 * height) + 1)][];
amaze[r]=new char[1];
amaze[r][c] = pos;

jaggedArray