【发布时间】:2014-04-27 05:27:34
【问题描述】:
我正在尝试为我的 Java 课程制作游戏,但我不断获得 NPE。我知道这意味着传递的变量之一是空值,但我不知道在哪里。我检查了所有涉及的变量。我相信初始化数组可能是一个问题,但我仍然没有看到我做错了什么。我检查了堆栈溢出,并且由于各种原因看到了 NPE,但我找不到适用于我的解决方案。
public class Inventory{
public int gold = 0;
private Item[] itemListArray = new Item[30];
private JButton[] itemButtonArray = new JButton[30];
private JButton buttonBack = new JButton("Back");
private static final String HOME = "Home";
public Inventory() {
for(int i = 1;i < 31; i++)
{
itemListArray[i].emptySlot = true; //Here is where the NPE hits
}
}}
这就是 NPE 要求错误的地方
public class Item {
protected String name = "";
protected int def = 0;
protected int stack = 100;
protected boolean stackable = false;
protected boolean consume = false;
boolean emptySlot = true;
protected ImageIcon icon;
public Item(){
}
public boolean isArmor()
{
if(def >= 1)
{
return true;
} else {
return false;
}
}
public boolean isConsumable()
{
if(consume = true)
{
return true;
} else {
return false;
}
}
public boolean isEmpty()
{
if(emptySlot = true)
{
return true;
} else {
return false;
}
}
这里是Item的声明。
请尽快回答我的问题,我似乎无法弄清楚。
【问题讨论】:
-
NPE 只有一个原因。您尝试使用的东西是
null -
Java array, NullPointerException? 的可能重复项或任何其他 100 次已被询问的重复项。