Trying to create the card game "UNO" in java. When a player plays a card, it should be removed from the hand with the other elements shifting to the left. It takes an int n as the parameter, which refers to the card being discarded. The method should change the cards array that I have specified as a field of the class. It's an array of objects which are the cards, or the players hand. When ran, it produces a nullPointerException. I know why the error is occurring, im just not sure how to fix it. I'm also trying to avoid the use of Array Lists. It also returns the card that is being discarded so it can be printed. Thanks.
public Card removeCardFromHand(int n)
{
Card c = cards[n];
Card[] tempCards = new Card[cards.length - 1];
for(int i = 0; i < n; i++)
{
tempCards[i] = cards[i];
}
for(int i = n; i < cards.length; i--)
{
tempCards[n] = cards[n + 1];
}
cards = tempCards;
return c;
}
Error Code:
java.lang.ArrayIndexOutOfBoundsException: 7
at Player.removeCardFromHand(Player.java:86)
at BUno.executeOnePlay(BUno.java:112)
at BUno.play(BUno.java:70)
at BUno.main(BUno.java:186)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
It's occurring because, in this case, the player had 7 cards. When the 7th one was removed, that 7th index was then empty. I wrote a similar method for adding a card when a player has to draw a card, which worked flawlessly. I am practicing for an upcoming exam, which doesn't cover array lists or vectors, so it's useless for me to use them.