I have an array of 10 Cards. In the process of a "turn", I add a Card to the array, and then remove a Card from the array (not always the same one.) The code works great for the first 6-7 turns, and then throws an IndexOutofBoundsException error when trying to get the specific Card from the array. It's something in the getCard, but why would it work fine previously, especially when I'm more or less keeping the same amount of objects in the array?
Print out: 1. J♥ 2. 10♣ 3. 10♦ 4. 9♠ 5. 9♦ 6. 7♥ 7. 7♣ 8. 6♣ 9. 5♣ 10. 2♦ 11. 2♥
playerDiscardCard = 11
(When displaying I am adding +1 to the index.)
ArrayList<Card> handCard = new ArrayList<Card>(10);
//Beginning of turn
playerHand.addCard(newCard);
//End of turn
int playerDiscardChoice = scanner.nextInt();
Card playerDiscardCard = playerHand.getCard(playerDiscardChoice-1);
playerHand.removeCard(playerDiscardCard);
//Methods
//where I initialize the playerHand
public ArrayList buildHand(Deck deck){
for (int i = 0; i < 10; i++)
{
Card newCard = deck.drawFromDeck();
handCard.add(newCard);
}
return handCard;
}
public ArrayList addCard (Card newCard){
handCard.add(newCard);
Collections.sort(handCard);
return handCard;
}
public Card getCard (int index){
Card returnCard = handCard.get(index);
return returnCard;
}
public ArrayList removeCard (Card newCard){
handCard.remove(newCard);
//Collections.sort(handCard);
return handCard;
}
//Exception error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10,
Size: 10
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Marty.company.Hand.getCard(Hand.java:18)
at Marty.company.Main.runHumanTurn(Main.java:103)
at Marty.company.Main.newGame(Main.java:41)
at Marty.company.Main.main(Main.java:15)