int playerNum,cardNum;
Cards card=null;
for(playerNum=0;playerNum<=NUMPLAYERS-1;playerNum++)
{
//some code...
for(cardNum=1;cardNum<=5;cardNum++)
{
card=( deckOfCards.deal() );
players[playerNum].setHand_1by1(card);//I get NullPointerException for using the method here
//some code...
}
}
class Hand
{
private Cards[] hand=new Cards[5];
private int counter;
//no constructor, just a setter.
public void setHand_1by1(Cards card)
{
if(counter>=hand.length)
{
System.out.printf("Hand is full");
}
else
{
hand[counter]=card;
counter++;
}
}
//some code...
}
我了解到,NullPointerException
当您尝试取消引用什么都没有指向的东西时(例如null
),您会得到。
1),但card
的Cards
类型指向的东西,由于方法deckOfCards.deal()
所以这不是问题,必须有一些的方法。
2)在中setHand_1by1()
,hand[counter]
属于卡片类型。我所做的就是使它指向包含Cards
该else
块中类型数据的有效内存。
为什么我会出现NullPointerException
错误?
编辑:只是显示我如何创建我的players
:
Hand[] players=new Hand[NUMPLAYERS];
您需要一个Hand
对象引用players[playernum]
才能在其上调用Hand
方法。
在players
您创建(类型的数组Hand
),实际上只是可以容纳一个数组Hand
(或它的子类)的对象引用。最初,引用都是all null
,您需要自己填充它们。
关于对象数组注释,请注意,从没有对象数组,只有对象引用数组。引用指向对象实际驻留的位置(通常是堆)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句