[英]Null pointer exception thrown at enum static method
我試圖使用復合框和數字單調來添加數獨難題。 我有這樣的事情:
class SudokuPuzzle {
SudokuBox[][] grid = new SudokuBox[3][3];
public void setDigit(int row, int col, int digit) {
SudokuDigit a = SudokuDigit.SudokuDigitfromInt(digit);
grid[row / 3][col / 3].setDigit(row % 3, col % 3, a);
}
}
class SudokuBox {
SudokuDigit[][] grid = new SudokuDigit[3][3];
public void setDigit(int row, int col, SudokuDigit digit) {
grid[row][col] = digit;
}
}
enum SudokuDigit {
one,two,three,four,five,six,seven,eight,nine;
public static SudokuDigit SudokuDigitfromInt(int digit) {
switch(digit) {
case 1: return one;
case 2: return two;
case 3: return three;
case 4: return four;
case 5: return five;
case 6: return six;
case 7: return seven;
case 8: return eight;
case 9: default: return nine;
}
}
public static int IntfromSudokuDigit(SudokuDigit digit) {
switch(digit) {
case one: return 1;
case two: return 2;
case three: return 3;
case four: return 4;
case five: return 5;
case six: return 6;
case seven: return 7;
case eight: return 8;
case nine: default: return 9;
}
}
}
NullPointerException
拋出在SudokuPuzzle.setDigit()
。 在此,將課程的無關部分刪除。 為什么會引發這樣的異常?
class SudokuPuzzle {
SudokuBox[][] grid=new SudokuBox[3][3];
// here you have to assign `SudokuBox` references to your array array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
grid[i][j] = new SudokuBox();
}
}
public void setDigit(int row,int col,int digit) {
SudokuDigit a=SudokuDigit.SudokuDigitfromInt(digit);
grid[row/3][col/3].setDigit(row%3,col%3,a);
}
}
首先將SudokuBox
引用分配給數組,然后可以將值設置為其索引。 它將避免NullPointerException
。
您需要在實例數組之后實例化數組的每個元素:
SudokuBox[][] grid=new SudokuBox[3][3];
for(int y=0; y<3; y++) {
for(int x=0; x<3; x++) {
grid[y][x] = new SudokuBox();
}
}
與基本類型(如int,boolean,long等)不同,對象需要是數組中每個元素的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.