数组索引超出范围 - 将2d转换为1d

时间:2014-10-08 15:00:57

标签: java arrays multidimensional-array indexoutofboundsexception dimensional

我不确定为什么我会得到一个超出界限的数组索引。根据我的理解,我的双数组大小为3,所以索引从0到2.在我的isSolvable方法中,我尝试计算双数组中的反转次数,其中反转是任意一对块i和j,其中我< j但是当我按照行主要顺序考虑董事会时,我出现在j之后。我尝试通过将我的2d数组转换为1d数组来做到这一点,这样我就可以遍历1d数组来计算所有的反转。如果反转是偶数(在奇数编号的板内)那么8拼图板是可解的。我的for循环只计算到数组的长度,所以我不完全确定我是如何获得Array Index Out Of Bounds异常的。

提前致谢!每个答案都有助于防止我将来犯同样的错误。

int N = 3; 
static int [][] copy; 

//construct a board from an N-by-N array of blocks 
//(where blocks[i][j] = block in row i, column j) 
public Board(int[][] blocks){
    blocks =  new int[N][N]; //creates array of size N

    //generates random numbers 0 inclusive to # exclusive 
    //creates ArrayList - shuffle used to prevent repeating of numbers 
    List<Integer> randomList = new ArrayList<>(); 
    for (int i = 0; i < 9; i++){
        randomList.add(i); 
    }
    int counter = 0; 
    Collections.shuffle(randomList);
    for (int i = 0; i < blocks.length; i++){
        for (int j = 0; j < blocks[i].length; j++){
            blocks[i][j] = randomList.get(counter); 
            counter++;
        }
    }
    copy = blocks.clone(); 
}


 //is the board solvable? 
 public boolean isSolvable(){
    int inversions = 0; 
    List<Integer> convert = new ArrayList<>(); // used to convert 2d to 1d 
    for (int i = 0; i < copy.length; i++){
        for (int j = 0; i < copy[i].length; j++){
            convert.add(copy[i][j]); //ARRAYINDEXOUTOFBOUNDSEXCEPTION: 3 
        }
    }
    for (int i = 0; i < copy.length; i++){ //counts the number of inversions 
        if (convert.get(i) < convert.get(i-1)){
            inversions++; 
        }
    }
    if (inversions % 2 == 0){
        return true; //even 
    }
    return false; //odd 
}

//unit test 
public static void main(String[] args){
    //prints out board 
    printArray(); 
    Board unittest = new Board(copy); 
    unittest.isSolvable(); //ARRAYINDEXOUTOFBOUNDSEXCEPTION: 3 



}

2 个答案:

答案 0 :(得分:4)

isSolvable的内部循环中有一个拼写错误:

for (int j = 0; i < copy[i].length; j++){
                ^
                |
           should be j

应该是:

for (int j = 0; j < copy[i].length; j++){

答案 1 :(得分:0)

数组索引j超出范围,因为在检查j时,您不断增加i < copy[i].length的值。由于此值保持为true,因此j将递增为数组,该数字是数组copy[i][j]的超出范围的索引。