问题描述
我问了一个关于生命游戏实现代码的问题.建议的解决方案解决了我的问题,但又创建了一个新问题.
现在,如果我尝试调用 getCell()
方法,我会得到一个 java.lang.NullPointerException
.如何避免此异常?
使用我使用的相应代码和解决方案代码链接到我之前的问题:我如何访问我的 getCell 方法中的元胞数组?(Java)
I have asked a question about my code for a Game of Life Implementation. The suggested solution solved my problem but created a new one.
Now if I try to call the getCell()
method I get a java.lang.NullPointerException
.How can I avoid this exception?
Link to my previous question with the corresponding code and solution code that I used:How can I access the Cell Array in my getCell method? (Java)
或者如果您只想要代码:
Or if you just want the code:
public class GameMap {
private Cell[][] cellArray;
private static Cell[][] buildCellArray(int width, int height){
Cell[][] cellArray = new Cell[width][height];
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
}
推荐答案
buildCellArray(sizeX, sizeY);
这确实构建了一个新数组并返回它,但您没有将它分配给它需要转到的那个字段.您只是丢弃了结果,该字段保持原样 (null
).
That does indeed build a new array and returns it, but you are not assigning it to that field it needs to go to. You are just throwing away the result, and the field stays what it was (null
).
你需要做的
cellArray = buildCellArray(sizeX, sizeY);
您有一个与静态方法中的字段同名的局部变量,这有点令人困惑.但它们完全无关.尽量避免这种阴影.您可以将名称更改为例如
It is a bit confusing that you have a local variable with the same name as the field in your static method. But they are completely unrelated. Try to avoid that kind of shadowing. You could change the name to for example
private static Cell[][] buildCellArray(int width, int height){
Cell[][] newCellArray = new Cell[width][height];
这篇关于如何在我的代码中避免 java.lang.NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!