我的代码编译得很好,但是当我运行它时出现以下错误:
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0 在Sudoku。(Sudoku.java:20)在Test.main(Test.java:7)
代码如下:
主要测试类:
public class Test {
public static void main(String[] args) {
Sudoku puzzle;
int[][] entries = {{1,0,0,0},{0,0,0,3},{0,0,4,0},{0,4,0,0}};
puzzle = new Sudoku(2,2,entries);
boolean somethingChanged=true;
while(somethingChanged) {
somethingChanged=false;
System.out.println(puzzle);
for (int i=0; i<puzzle.size; i++)
for(int j=0; j<puzzle.size; j++)
if(puzzle.oneOption(i, j)!=puzzle.EMPTY) {
// exactly one value can be filled in at location i,j
// do this now, and record that something has changed
// compared to the previous iteration of the while loop
puzzle.setValue(i,j,puzzle.oneOption(i,j));
somethingChanged=true;
}
}
// if oneOption is implemented correctly, the puzzle is now solved!
System.out.println(puzzle);
}
}
和我未注释的Sudoku Class:
class Sudoku {
int cellHeight, cellWidth, size,EMPTY = 0;
int [][] sudGrid = new int[cellHeight * cellWidth][cellHeight * cellWidth];
int [][] cellGrid = new int [cellHeight][cellWidth];
public Sudoku(int a, int b){
cellHeight = a;
cellWidth = b;
size = cellHeight*cellWidth;
}
public Sudoku(int a, int b, int array[][]){
cellHeight = a;
cellWidth = b;
size = cellHeight*cellWidth;
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
int temp = array[i][j];
sudGrid[i][j] = temp;
}
}
}
public Sudoku(){
cellHeight = 3;
cellWidth = 3;
size = cellHeight*cellWidth;
for(int i = 0; i<size; i++)
for(int j = 0; j<size; j++)
sudGrid[i][j] = 0;
}
public void setValue(int r,int c, int v){
sudGrid[r][c] = v;
}
public int getValue(int r, int c){
return sudGrid[r][c];
}
public void clear(int r, int c){
sudGrid[r][c] = EMPTY;
}
public String toString(){
String message = "";
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
message = message + sudGrid[i][j];
if (j == cellWidth){
message = message + " ";
}
}
message = message + "\n";
}
return message;
}
public int oneOption(int r, int c){
return 1;
}
}
很抱歉,我知道这是很多代码要在屏幕上显示,但我没有在阵列上做过很多,更不用说二维了。我知道我的oneOption()
方法目前什么也没做,我只是需要它来编译,但错误在哪里,是
int temp = array[i][j];
sudGrid[i][j] = temp;
和
int[][] entries = {{1,0,0,0},{0,0,0,3},{0,0,4,0},{0,4,0,0}};
puzzle = new Sudoku(2,2,entries);
现在我假设条目数组声明的位置是正确的,因为这是我的讲师为我们设置的代码,我们只设计了Sudoku类。我试图使条目数组的值,进入sudGrid数组,我假设我做得正确,但我得到异常错误,
任何想法?
答案 0 :(得分:1)
您将Sudoku.size
设置为拼图中的整个单元格数,然后尝试读取那么多行和列。您只需迭代到列数和行数。
答案 1 :(得分:1)
您的subgrid
被定义为零长度二维数组,因此您无法在其中放置任何内容。
见这里:
int cellHeight, cellWidth, size,EMPTY = 0;
int [][] sudGrid = new int[cellHeight * cellWidth][cellHeight * cellWidth];
默认情况下, cellHeight
和cellWidth
初始化为零,然后您创建一个new int[0*0][0*0]
数组。
将构造函数更改为以下内容:
public Sudoku(int a, int b, int array[][]){
cellHeight = a; // Changing these two instance variables will *NOT*
cellWidth = b; // retrofit your subGrid to a new size.
size = cellHeight*cellWidth;
subGrid = new int[size][size];
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
int temp = array[i][j];
sudGrid[i][j] = temp;
}
}
}