Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ArrayIndexOutofBounds在移动机器人通过ASCII迷宫时出错_Java_Indexoutofboundsexception_Robot - Fatal编程技术网

Java ArrayIndexOutofBounds在移动机器人通过ASCII迷宫时出错

Java ArrayIndexOutofBounds在移动机器人通过ASCII迷宫时出错,java,indexoutofboundsexception,robot,Java,Indexoutofboundsexception,Robot,我一直在研究一个机器人,让它穿过一个总是试图向右移动的迷宫,如果它不能向右移动,它会一直走,如果它不能一直走,它会尝试向左走,最后如果没有其他选择,它会向后移动 我有几个不同的类,将尝试显示错误在哪里。我将把完整的代码也放在一个粘贴箱中 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at hw2sp14.Maze.openCell(Maze.java:69) at hw2sp14.R

我一直在研究一个机器人,让它穿过一个总是试图向右移动的迷宫,如果它不能向右移动,它会一直走,如果它不能一直走,它会尝试向左走,最后如果没有其他选择,它会向后移动

我有几个不同的类,将尝试显示错误在哪里。我将把完整的代码也放在一个粘贴箱中

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类非常庞大,所以我将把它放在一个粘贴箱中

如果我需要贴满浆糊,我可以根据要求。谢谢

阅读有关条件和&&operator的信息。然后以这种方式重写您的条件:

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

您必须先检查行和列,然后才能将其用作数组索引。

您还没有向我们展示足够的代码。基本上,currentMaze没有传递给该方法的行和列的条目;但由于您没有向我们展示currentMaze是在哪里创建的,或者行和列是什么,所以无法告诉您哪里做错了。您可以做的最好的事情是使用调试器逐步完成代码。这将使您能够立即看到出了什么问题。我之所以选择VTC'ed,是因为您没有提供足够的代码来重现问题。谢谢!这让它运行起来了!