【问题标题】:Array index out of bounds - converting 2d to 1d [closed]数组索引超出范围 - 将 2d 转换为 1d [关闭]
【发布时间】:2014-12-03 07:21:10
【问题描述】:

我不太确定为什么会出现数组索引越界异常。据我了解,我的双精度数组的大小为 3,因此索引从 0 到 2。在我的 isSolvable 方法中,我尝试计算我的双精度数组中的反转数,其中反转是任何一对块 i 和 j,其中i

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

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 



}

【问题讨论】:

    标签: java arrays multidimensional-array indexoutofboundsexception dimensional


    【解决方案1】:

    isSolvable 的内循环中有错字:

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

    应该是:

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

    【讨论】:

      【解决方案2】:

      数组索引j 超出范围,因为您在检查i &lt; copy[i].length 时不断增加j 的值。由于该值保持为真,j 将递增到一个数字,该数字是数组 copy[i][j] 的索引超出范围。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-28
        • 2017-11-02
        • 2017-07-29
        • 2017-07-30
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多