gpt4 book ai didi

Java:NullPointerException 二维对象数组甚至数组已初始化并填充

转载 作者:行者123 更新时间:2023-11-29 03:25:50 26 4
gpt4 key购买 nike

在 forest() 方法中,我创建了一个二维对象数组,然后填充它。我确定数组已填充,因为我可以在方法 forest() 的类 Forest 中以及方法 setTree() 的类 Tree 中显示数组的内容,如下所示。不幸的是,我无法通过方法 showContentOfTree() 或其他地方获取此内容。出现错误: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)

最佳答案

你是shadowing forest 方法中的 tree 变量。

public forest(){
setLayout(null);
loadImage = new LoadImage();
loadImage.Image();
tree = new Tree[16][16]; //<-- remove Tree[][]

关于Java:NullPointerException 二维对象数组甚至数组已初始化并填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21043139/

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