[英]Getting a NullPointerException, not sure why
首先我实例化一个游戏状态
class GameState extends state{
ArrayList<Level> levels;
int currentLevelID;
public GameState() {
stateID = 2;
levels = new ArrayList<Level>();
createLevels();
currentLevelID = 0;
}
创造关卡
public void createLevels(){
try {
this.levels.add(new NormalLevel(0, 10, 10, null, null, new EmptyTile(1, 1, 1, 1, null) ));
} catch (IOException e) {
e.printStackTrace();
}
}
使用这段代码(忘了技术术语大声笑)
//level is the superclass of normallevel or whatever i named the default level
public Level(int id, int height, int width, ArrayList<TileEntity> tiles, ArrayList<MobileEntity> mobiles, TileEntity fillBlock){
this.height = height;
this.levelID = id;
this.width = width;
if(tiles != null){
this.tiles = tiles;
} else {
tiles = new ArrayList<TileEntity>();
try {
tiles.add(new EmptyTile(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
try {
mobiles.add(new DefaultEntity(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fillBlock != null){
this.tiles = new ArrayList<TileEntity>();
this.fillWith(fillBlock);
}
}
public void fillWith(TileEntity tile){
for(int i = 0; i < this.height; i++){
for(int j = 0; j < this.width; j++){
for(int k = 0; k < this.tiles.size(); k++){
if (this.tiles.get(k).y == i && this.tiles.get(k).x == j){
break;
}
if(k == this.tiles.size()){
tile.x = j;
tile.y = i;
this.tiles.add(tile);
}
}
}
}
}
然后我尝试更新水平
public void update(){
this.draw();
for(int i = 0; i < this.tiles.size(); i++){
this.tiles.get(i).update();
}
for(int i = 0; i < this.mobiles.size(); i++){ //nullpointerexception here
this.mobiles.get(i).update();
}
this.specialUpdate();
}
但是我在注释行上出错。 我很困惑,地狱,将不胜感激:)
您的mobiles
对象为null,因为在以下代码中
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
在其他情况下,您分配的是本地变量mobiles
而不是this.mobiles
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
try {
mobiles.add(new DefaultEntity(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
如果mobiles != null
,则分配实例变量( this.mobiles
),如果是,则创建一个新List
,但将其分配给局部变量( mobiles
),这就是为什么列表永远不会到达实例变量的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.