2012-12-28 186 views
0

为了避免空指针的问题,我以为我初始化了数组中的所有对象,但似乎我在某处出错了。初始化二维数组对象

继承此类的代码。在数组外部使用MapBlock对象时,它可以正常工作。

执行是当它试图访问更新方法中的对象。

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 ++; 
      } 

     } 
    } 

}

谢谢你的任何反馈

+0

发布完整的例外消息。 – Mob

+0

你在哪里得到这个异常 –

+0

其空! 异常在线程 “主” 显示java.lang.NullPointerException \t在Game.update(Game.java:41) \t在Main.update(Main.java:65) \t在Main.gameLoop(Main.java:59 )Main.main(Main.java:22)处的 \t。它在同一行上运行mapObjects [0] [0] .update();对不起,它的所有聚集在一起不能发布 –

回答

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方法没有实例化。

+0

谢谢你,我的弱点!它没有发生在我身上,if()可能是问题的一部分。它现在的作品,现在谢谢你,我也必须改变,如果(我<24)如果(我<23)停止出界的错误,我只是想出了为什么输入这个笑声。再次感谢! –

+0

@richilonsdale只是在未来的建议;在任何菊花链风格的if-else if-else if-'子句中添加最后的'else',并且如果你不希望在那里抛出/打印错误; 'else {System.out.println(“这不应该发生。”); }'。这样你就会更快地得到这个问题的警报,并且在它的实际来源。 – NominSim

+0

这是一个很好的建议,非常感谢你的帮助,iv今天从这个网站的人们学到了更多,然后是最近几周阅读书籍并观看YouTube的信息。 –