简体   繁体   中英

Null pointer exception thrown at enum static method

I tried to impement a sudoku puzzle using composite boxes and singletons of digits. I have something like that:

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 is thrown at SudokuPuzzle.setDigit() . Irrelevant parts of the classes are stripped down here. Why is such an exception thrown?

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

First assign SudokuBox references to your array then you can set value to it's index. It will avoid NullPointerException .

You need to instance each element of your array after instance the array:

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

Different from primitive types (like int, boolean, long, etc), Objects need to be instance for each element of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM