gpt4 book ai didi

java - 收到 NullPointerException,不知道为什么

转载 作者:行者123 更新时间:2023-12-01 23:20:44 28 4
gpt4 key购买 nike

首先我实例化一个游戏状态

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

关于java - 收到 NullPointerException,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20668870/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com