【发布时间】: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