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...
}
I understand that you get a NullPointerException
when you try to dereference something that's pointing to nothing(ie null
).
1)But card
of Cards
type is pointing to something due to the method deckOfCards.deal()
so that's not the problem, must be something in the method.
2)In the setHand_1by1()
, hand[counter]
is of Cards type. All I did was make it point to valid memory containing data of Cards
type in the else
block.
Why am I then getting a NullPointerException
error?
Edit:
Just showing how I created my players
:
Hand[] players=new Hand[NUMPLAYERS];