2014-04-27 45 views
-3

我正在尝试为我的Java类制作游戏,但我一直在获取NPE。我知道这意味着其中一个变量被传递为null,但我不知道在哪里。我已经检查了所有涉及的变量。我相信这可能是一个初始化数组的问题,但我仍然没有看到我做错了什么。我已经检查过堆栈溢出,并且由于各种原因已经看到NPE,但是我找不到适用于我的解决方案。当通过数组传递布尔值时发生java.lang.NullPointerException

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

这里是项目的申报。

请回答我的问题,我似乎无法弄清楚。

+1

NPE的确有一个原因*。你试图使用的是'null' –

+0

可能重复的[Java数组,NullPointerException?](http://stackoverflow.com/questions/15170192/java-array-nullpointerexception)或任何其他100次这个已被问到。 –

回答

1

仅仅实例化数组是不够的,您还必须使用对象填充它。否则,每个索引默认包含null。

private Item[] itemListArray = new Item[30]; 
for (int i = 0; i < itemListArray.length; i++) { 
    itemListArray[i] = new Item(); 
} 
1

您使用private Item[] itemListArray = new Item[30];实例化您的数组,其中创建一个包含30个空条目的Item类型的数组。

当您在构造函数的循环中调用itemListArray[i].emptySlot时,您正在从空对象访问变量。

在访问任何变量或调用任何方法之前,必须在构造函数(或其他地方)的循环中实例化数组中的任何Item对象。

另外您的for循环正在跳过第一个元素。 Java中的第一个元素的索引为0.

2

此代码只是创建一个包含null值的数组,你需要初始化数组中的每个单独的值。

for(int i = 1;i < 31; i++) 
{ 
    itemListArray[i].emptySlot = true; //Here is where the NPE hits 
} 

而这个周期会因为在Java有效的数组索引后引起ArrayIndexOutOfBoundsException从0开始,去array.length-1(0至29日在你的情况下),而该代码会试图访问itemListArray[ 30 ]

0

我猜你可能并不了解java.you中的初始化只是初始化一个数组,但它并没有引用真实的对象。

这样的代码将有助于:

for(int i = 1;i < 31; i++){ 
     Item item = new Item(); 
     item.emptySlot = true; 
     itemListArray[i] = item; //Here is where the NPE hits 
} 

尝试使用项目类的构造函数要好得多,希望它的工作。

0

创建一个对象数组默认将它们全部设为null。您需要将一个对象放入数组的每个元素中以消除此问题。

for (int i = 0; i < itemListArray.length; i++) { 
    itemListArray[i] = new Item(); 
} 

for (int j = 0; j < itemButtonArray.length; j++) { 
    itemButtonArray[j] = new JButton(); 
}