Java 枚举静态方法引发空指针异常

Java 枚举静态方法引发空指针异常,java,enums,nullpointerexception,Java,Enums,Nullpointerexception,我试着用复合框和一组数字拼凑出一个数独游戏。我有这样的想法: 数独游戏 数独盒子 数独数字 NullPointerException被抛出到SudokuPuzzle.setDigit()。课程中不相关的部分在这里被剥离。为什么会引发这样的异常?类SudokuPuzzle{ class SudokuPuzzle { SudokuBox[][] grid=new SudokuBox[3][3]; // here you have to assign `SudokuBox` references

我试着用复合框和一组数字拼凑出一个数独游戏。我有这样的想法:

数独游戏 数独盒子 数独数字
NullPointerException
被抛出到
SudokuPuzzle.setDigit()
。课程中不相关的部分在这里被剥离。为什么会引发这样的异常?

类SudokuPuzzle{
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[][]网格=新的SudokuBox[3][3]; //在这里,您必须为数组分配'SudokuBox'引用
对于(int i=0;i您需要在数组的实例之后再实例数组的每个元素:

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();
 }
}

SudokuBox[][]网格=新的SudokuBox[3][3];

对于(int y=0;y
SudokuBox[]]grid=new SudokuBox[3][3];
每个引用仍然是
null
。您需要初始化每个引用。
grid[row/3][col col/3]=new SudokuBox();grid[row/3][col col 3]。设置位数(row%3,col 3,a);
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;
        }
    }
}
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[][] grid=new SudokuBox[3][3];
for(int y=0; y<3; y++) {
 for(int x=0; x<3; x++) {
  grid[y][x] = new SudokuBox();
 }
}