【问题标题】:array index out of bounds exception , is this meant to happen?数组索引越界异常,这是要发生的吗?
【发布时间】:2012-06-05 23:23:26
【问题描述】:

我试图在 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());
    }

【问题讨论】:

  • 那么,此时xy 的值是多少,涉及的数组的长度是多少?
  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) 复制/粘贴错误信息。
  • 我认为 x 应该是 y 所在的位置,反之亦然

标签: java indexoutofboundsexception


【解决方案1】:

你的变量有问题。你最外面的循环是基于行的,但是你在你初始化为列大小的数组中使用它

【讨论】:

    【解决方案2】:

    你初始化了数组

    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]

    【讨论】:

    • @Liam 是的,完全正确。顺便说一句,这就是为什么在大多数地方要避免使用像“x”和“y”这样的变量。想想如果把它写成for (int row=1; row &lt; (2*rows); row++) 等会更清楚。
    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多