初始化2d对象数组

时间:2012-12-28 18:48:46

标签: java arrays nullpointerexception multidimensional-array

我正在尝试一个空指针,我以为我已经启动了数组中的所有对象,但似乎我在某些地方出错了。

这是本课程的代码。在数组外部使用MapBlock对象时,它可以正常工作。

execption是在尝试访问update方法中的对象时。

public class Game { 
    private Scanner scan;

    // map stuff
    MapBlock[][] mapObjects;


    // List of Textures
    Texture path;
    Texture tower;
    Texture grass;

    Game(){ 
        // Textures
        path = loadTexture("path");
        tower = loadTexture("tower");
        grass = loadTexture("grass");



        mapObjects = new MapBlock[24][16];

        loadLevelFile("level1");        

    }

    public void update(){
        if(mapObjects[0][0] == null)
            System.out.println("its null!!!");
        mapObjects[0][0].update();
    }

    public void render(){
        mapObjects[0][0].render();      
    }




    private Texture loadTexture(String imageName){
        try {
            return TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + imageName + ".png")));
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException r){
            r.printStackTrace();
        }
        return null;
    }

    private void loadLevelFile(String mapName){
        try {
            scan = new Scanner(new File("res/" + mapName + ".txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Could not open "+ mapName +" file!");
            e.printStackTrace();
        }

        String obj;
        int i = 0, t = 0;

        while(scan.hasNext()){
            obj = scan.next();

            if(obj == "o"){
                mapObjects[i][t] = new MapBlock("GRASS", t*32, i*32, grass);

            }else if(obj == "x"){
                mapObjects[i][t] = new MapBlock("PATH", t*32, i*32, path);

            }else if(obj == "i"){
                mapObjects[i][t] = new MapBlock("TOWER", t*32, i*32, tower);                    
            }

            if(i < 24){
                i++;
            }else{
                i = 0;
                t ++;
            }

        }
    }
}

感谢您提供任何反馈

1 个答案:

答案 0 :(得分:4)

loadLevelFile方法中:

-> if(obj == "o"){
// ...
-> }else if(obj == "x"){
// ...  
-> }else if(obj == "i"){
// ...
}

您要将字符串与==进行比较,而不是.equals(),这可能会导致mapObjects数组的实例化不会发生。

尝试将其更改为:

if(obj.equals("o")){
// ...
}else if(obj.equals("x")){
// ...  
}else if(obj.equals("i")){
// ...
}

此处发生错误:

if(mapObjects[0][0] == null)
    System.out.println("its null!!!");
mapObjects[0][0].update(); <- Error happens here

因为mapObjects[0][0]上的对象仍然是null,因为loadLevelFile方法没有实例化它。