[英]NullPointerException when trying to set a double array in java
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 不断收到NullPointer错误
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();
}
}
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".
二维数组[i] [j]基本上表示“我的数组有i个数组,每个数组都有j个值”。 If there's no i, it doesn't mean anything.
如果没有我,那什么也没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.