我一直在研究一个穿过迷宫的机器人,它总是尝试向右移动,如果它不能向右移动,它会直走,如果它不能直走,它会尝试向左移动,然后最后,如果没有其他选项可用,它将向后移动。
我有几个不同的课程,并会尝试显示错误在哪里。我也会将完整的代码放入 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 类很大,所以我要把它放在一个粘贴箱中。 http://pastebin.com/WEmzJR7v
如果我需要粘贴完整的粘贴,我可以根据要求进行。谢谢
阅读条件和
&&
运算符。然后这样重写你的条件:
if(row>=0 && row<numRows && col>=0 && col<numCols && currentMaze[row][col] == ' '){
open = true;
}
您必须检查
row
和col
才能将其用作数组索引。