This is the relevant code I think
class Sudoku {
int[][] grid;
void generateSudokuFromInput()
{
grid = new int[][] <--- java.lang.NullPointerException at Sudoku.generateSudokuFromInput(Sudoku.java:309)
{
(...)
}
}
void solveIt() {
generateSudokuFromInput();
}
}
Keep getting NullPointer error
When declaring multidimensional array, you must specify all the dimensions except the last one.
Eg
grid = new int [3][];
This will work nicely.
As an alternative to declaring the array size later (as described in other answers), you can also just initialize your array when declaring it:
class Sudoku {
int[][] grid = {
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}
};
void generateSudokuFromInput() {
// just set the values on grid, e.g. grid[0][0] = 9
}
void solveIt() {
generateSudokuFromInput();
}
}
To create an array you must have to specify the subscript value.
grid = new int[2][];
grid[0]=new int[2];
grid[1]=new int[5];
or
grid=new int[3][3];
To learn more about arrays refer this document.
You need to provide size for the first dimension:
grid = new int[3][];
Else, how do you expect the second dimension to work? A 2-dimensions array [i][j] basically means "My array has i arrays, each of them have j values". If there's no i, it doesn't mean anything.
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.