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

Java 数组索引超出范围-将2d转换为1d,java,arrays,multidimensional-array,indexoutofboundsexception,dimensional,Java,Arrays,Multidimensional Array,Indexoutofboundsexception,Dimensional,我不太清楚为什么会出现数组索引越界异常。据我所知,我的双数组大小为3,因此索引从0到2。在我的isSolvable方法中,我尝试计算我的双数组中的反转数,其中反转是任何一对块I和j,其中I

我不太清楚为什么会出现数组索引越界异常。据我所知,我的双数组大小为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 



}
int N=3;
静态int[][]拷贝;
//从N×N块阵列构造电路板
//(其中块[i][j]=第i行第j列中的块)
公用电路板(int[][]块){
blocks=newint[N][N];//创建大小为N的数组
//生成包含0到#互斥的随机数
//创建用于防止数字重复的ArrayList-shuffle
List randomList=新建ArrayList();
对于(int i=0;i<9;i++){
随机列表。添加(i);
}
int计数器=0;
集合。随机移动(随机列表);
对于(int i=0;i
您在
可解决的内部循环中有一个输入错误

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

for (int j = 0; j < copy[i].length; j++){
for(int j=0;j
您在
可解决的内部循环中有一个输入错误

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

for (int j = 0; j < copy[i].length; j++){
for(int j=0;j
数组索引
j
超出范围,因为您在检查
i
时不断增加
j
的值。由于该值保持为真,j将增加到数组
copy[i][j]的索引超出范围的数字

数组索引
j
将越界,因为您在检查
i
时不断增加
j
的值。由于该值保持为真,j将增加到一个数字,该数字是数组
copy[i][j]的越界索引