得到一个NullPointerException,不知道为什么

时间:2013-12-18 21:33:33

标签: java nullpointerexception

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

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();
    }
}

使用这段代码(忘了技术术语lol)

    //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();
    }

但是我在注释行上收到错误。我很困惑,我会很感激帮助:)

2 个答案:

答案 0 :(得分:2)

您的mobiles对象为null,因为在以下代码中

if(mobiles != null){
        this.mobiles = mobiles;
} else {
    mobiles = new ArrayList<MobileEntity>();
情况下,您指定了局部变量mobiles而不是this.mobiles

答案 1 :(得分:1)

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 ),这就是列表永远不会到达实例变量的原因。