Java 数组索引超出范围-从2d到1d
我正在与普林斯顿大学推出的algs4 8字谜项目合作。我在第二个for循环中得到一个数组索引越界异常。是否有人看到引发此异常的问题?我的board类+相关方法如下所示:Java 数组索引超出范围-从2d到1d,java,arrays,Java,Arrays,我正在与普林斯顿大学推出的algs4 8字谜项目合作。我在第二个for循环中得到一个数组索引越界异常。是否有人看到引发此异常的问题?我的board类+相关方法如下所示: public class Board { private final int[][] blocks; private final int N; // construct a board from an N-by-N array of blocks // (where blocks[i][j] = block in ro
public class Board {
private final int[][] blocks;
private final int N;
// 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){
N = blocks.length;
this.blocks = new int[N][];
for (int i=0; i<N; i++){
this.blocks[i] = Arrays.copyOf(blocks[i], N);
}
}
// board dimension N
public int dimension(){
return this.N;
}
//is the board solvable?
public boolean isSolvable(){
int inversions = 0;
List<Integer> convert = new ArrayList<>(); // convert 2d to 1d
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
convert.add(blocks[i][j]);
}
}
for (int i = 0; i < blocks.length; i++){ //counts the number of inversions
if (convert.get(i) < convert.get(i-1)){ //ARRAYINDEXOUTOFBOUNDS -1
inversions++;
}
}
if (inversions % 2 == 0){
return true; //even
}
return false; //odd
}
公共课程委员会{
专用最终int[][]块;
私人终审法院;
//从N×N块阵列构造电路板
//(其中块[i][j]=第i行第j列中的块)
公用电路板(int[][]块){
N=块长度;
this.blocks=newint[N][];
for(inti=0;iconvert.get(i-1)
在i==0时超出范围
您可能应该更改循环的开始索引:
for (int i = 1; i < blocks.length; i++){ //counts the number of inversions
if (convert.get(i) < convert.get(i-1)){
inversions++;
}
}
for(int i=1;i
所以当i=0
时,在convert.get(i-1)
中的i-1
是什么?它尝试查找任何数组/列表/字符串中都不存在的索引-1。