枚举静态方法抛出空指针异常

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

NullPointerExceptionSudokuPuzzle.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 等)不同,对象需要为数组的每个元素实例化。