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

时间:2015-01-04 12:14:26

标签: java enums nullpointerexception

我尝试使用复合框和数字单例来强制数独谜题。我有类似的东西:

SudokuPuzzle

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

SudokuBox

class SudokuBox {
    SudokuDigit[][] grid = new SudokuDigit[3][3];

    public void setDigit(int row, int col, SudokuDigit digit) {
        grid[row][col] = digit;
    }
}

SudokuDigit

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投放{p> SudokuPuzzle.setDigit()。课程的不相关部分在这里被删除。为什么抛出这样的例外?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您需要在实例数组之后实例化数组的每个元素:

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