java - 数组索引越界异常,这是注定要发生的吗?

标签 java indexoutofboundsexception

我试图用java测试一个程序,但我得到了一个数组索引越界异常,我认为不应该抛出该异常。看看这段代码并告诉我是否遗漏了什么? eclipse 告诉我错误被抛出在我添加了注释来显示它的位置

class maze{

private int cols; // number of columns in maze  
private int rows; // number of rows in maze
private String name;
private weightedGraph<Integer> graph;
private dijkstra solution;
public char[][] mazeStore;

public maze(String filename){

    try{

        FileReader r = new FileReader(filename);
        Scanner s = new Scanner(r);
        this.rows = s.nextInt();
        this.cols = s.nextInt();
        this.name = filename;


        this.mazeStore = new char[(2*rows)+1][(2*cols)+1];
        String line = s.nextLine();
        for(int k = 0; k < ((2*rows)+1); k++){

            char[] temp = line.toCharArray();

            for(int i = 0; i < temp.length; i++){
                mazeStore[k][i] = temp[i];
                line = s.nextLine();
            }
        }



        graph = new weightedGraph<Integer>(rows*cols); 


        for(int y = 1; y < 2*rows; y++){
            for(int x = 1; x < 2*cols; x++){
                if((x % 2 == 1) && (y % 2 == 0)){
                    if(mazeStore[x][y] != '-'){ // <<<<<<<<<<<<<<THIS IS WHERE THE ERROR IS THROWN 
                        int label = (x - 1) + (x / 2);
                        graph.addEdge(label, label+cols, 1);
                        graph.addEdge(label+cols, label, 1);
                    }
                }

                if((x % 2 == 0) && (y % 2 == 1)){
                    if(mazeStore[x][y] != '|'){
                        int label = ((x - 1) + (x / 2)) + (y / 2);
                        graph.addEdge(label, label+1, 1);
                        graph.addEdge(label+1, label, 1);
                    }
                }
            }
        }



        this.solution = new dijkstra(graph, 0); 


    }
    catch(FileNotFoundException e){
        System.err.println("FileNotFoundException: " + e.getMessage());
    }

最佳答案

您初始化了数组

new char[(2*rows)+1][(2*cols)+1] 

但是迭代它

for(int y = 1; y < 2*rows; y++){//y row iterator
    for(int x = 1; x < 2*cols; x++){//x col iterator

应该是这样 mazeStore[y][x] 不是 mazeStore[x][y]

关于java - 数组索引越界异常,这是注定要发生的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10838078/

相关文章:

Java 矩阵乘法 ArrayIndexOutOfBounds 异常

java - 新线程中的 KeyListener 用于捕获游戏输入

Java 改变 JPanel 的形状

c# - TCP 连接阶段失败(从 JAVA 客户端调用 Web 服务到 C# 服务器)

c - 对于 (*ptr)[],为什么 printf ("%p",(void*)ptr+1) 有效但 printf ("%p",ptr+1) 无效?

java - 具有不同表达式类型的嵌套开关: ArrayIndexOutOfBoundsException -4

java - 当服务器 VM 是默认选项时,为什么有 -server 选项?

jvm - 带有 jar 的可移植 JVM

java - 数组索引越界但不应该

java - 将 java 中的文件从本地 xml 文件解析为新文本文件时出现 ArrayOutOfBoundException