ArrayIndexOutOfBoundsException 在 ASCII 迷宫中移动机器人时出错

ArrayIndexOutOfBoundsException Error moving a robot through an ASCII maze

我一直在研究一个机器人来穿过一个总是试图向右移动的迷宫,如果它不能向右移动,它会直走,如果它不能直走它会尝试去左,最后如果没有其他选项可用,它将返回。

我有几个不同的 classes 并且会尝试显示错误所在。我也会把完整的代码放在一个 pastebin 中。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at hw2sp14.Maze.openCell(Maze.java:69)
    at hw2sp14.RightHandRobot.move(RightHandRobot.java:165)
    at hw2sp14.MazeDriver.main(MazeDriver.java:42)

public static void main(String[] args) throws IOException {
    File inputFile = getFile();  //sample: testmaze.txt
    Maze maze = new Maze(inputFile);
    System.out.println(maze);
    Robot bot = new RightHandRobot(maze);//this ties the robot to the maze it is in
    System.out.println(maze);

    for (int k = 0; k < 1000000 && !bot.solved(); k++) 
    //this limits the robot's moves, in case it takes too long to find the exit.
    {
        int direction = bot.chooseMoveDirection();
        if (direction >=0)  //invalid direction is -1
            bot.move(direction);
        System.out.println(maze);
        System.out.println(bot.getFacing());
        System.out.println("\n");
    }
}

public boolean openCell(int row, int col){
    boolean open = false;
    if(currentMaze[row][col] == ' ' && row>=0 && row<numRows && col>=0 && col<numCols){
        open = true;
    }
    return open;
}

RightHandRobot class 很大,所以我要把它放在一个 pastebin 里。 http://pastebin.com/WEmzJR7v

如果我需要全贴,我可以要求。谢谢

了解条件和 && 运算符。然后以这种方式重写您的条件:

if(row>=0 && row<numRows && col>=0 && col<numCols && currentMaze[row][col] == ' '){
    open = true;
}

您必须检查 rowcol 才能将其用作数组索引。