gpt4 book ai didi

java - 数组索引越界 - 将 2d 转换为 1d

转载 作者:行者123 更新时间:2023-12-01 18:25:48 26 4
gpt4 key购买 nike

我不太确定为什么会出现数组索引越界异常。据我了解,我的 double 组的大小为 3,因此索引从 0 - 2 开始。在我的 isSolvable 方法中,我尝试计算 double 组中的反转次数,其中反转是任意一对 block i 和 j,其中i < j 但当按行优先顺序考虑棋盘时,i 出现在 j 之后。我尝试通过将二维数组转换为一维数组来做到这一点,以便我可以遍历一维数组来计算所有反转。如果反转是偶数(在奇数尺寸的棋盘内),则 8 拼图板是可解的。我的 for 循环仅计算数组的长度,因此我不完全确定如何获得数组索引越界异常。

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

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



}

最佳答案

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

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

应该是:

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

关于java - 数组索引越界 - 将 2d 转换为 1d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26260169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com