在方法forest()中,我創建了一個二維數組對象,然後填充它。我確信該數組已填充,因爲我可以在方法forest()中的Forest類中顯示數組的內容,也可以在setTree()方法的Tree樹中顯示數組的內容,如下所示。不幸的是,我無法通過showContentOfTree()方法或其他方法獲取此內容。錯誤apears:空指針異常Java:NullPointerException二維數組對象甚至數組初始化並填充
問題是爲什麼發生,我應該改變?
public class Forest extends JPanel {
private LoadImage loadImage;
private Tree[][] tree;
public forest(){
setLayout(null);
loadImage = new LoadImage();
loadImage.Image();
Tree[][] tree = new Tree[16][16];
for (int y = 0; y < 16; y++){
for (int x = 0; x < 16; x++){
tree[x][y] = new Tree();
tree[x][y].setTree(loadImage.loadForest(x,y));
System.out.println("Tree species " + tree[x][y].treeSpecies);
//here System displays loaded treeSpecies successfully
}
}
showContentOfTree();
}
public void showContentOfTree(){
for (int y = 0; y < 16; y++){
for (int x = 0; x < 16; x++){
System.out.println("Tree species" + tree[x][y].treeSpecies);
//here System DOES NOT displays loaded treeSpecies:
//Error apears: java.lang.NullPointerException
//at Forest.showContentOfTree(Forest.java:31)
}
}
}
public class Tree{
String treeSpecies;
public void setTree(String treeSpecies){
this.treeSpecies = treeSpecies;
System.out.println("Tree species " + treeSpecies);
//here System also displays loaded treeSpecies successfully
}
}
堆棧跟蹤:
Exception in thread "main" java.lang.NullPointerException at Forest.showContentOfTree(Forest.java:31)
at Forest.<init>(Forest.java:26)
at Okno.<init>(Okno.java:19)
在Glowny.main(Glowny.java:10)
你可以發佈堆棧跟蹤嗎? –