javaindexoutofboundsexception

ArrayIndexOutOfBoundsException Error moving a robot through an ASCII maze


I've been working on a robot to move through a maze that always tries to move right, if it can't move right, it will go straight, if it can't go straight it will try to go left, and then finally it will move back if no other options are available.

I have a few different classes and will try to show where the error is. I'll put the full code in a pastebin as well.

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

The RightHandRobot class is huge so I'm going to put that in a pastebin. http://pastebin.com/WEmzJR7v

If I need to put full pastes, I can on request. Thanks


Solution

  • Read about conditions and && operator. Then rewrite your condition that way:

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

    You have to check row and col before you can use it as array index.