Before I get into anything, I just want to say that I am a newbie to Java (1 year) and Stack Overflow (about a few months), so if I am doing something wrong, please let me know!
Anyways, lets get into the problem. You see, I am building a Poker program, and I am at the point where I need to "deal" out cards to all of the players (the user and 4 bots). To make things as fast and efficient as possible, I decided to use a for loop to add all of the cards. I have also done the same thing for resetting the deck every hand, using the following code:
public String[] cardTypes = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"} ;
...
// The for loop below resets the deck by adding all of the cards by using the array "cardTypes" (Ace, 2, Queen, etc.)
for (int i = 0 ; i < poker.cardTypes.length ; i++) {
poker.deck.add(poker.cardTypes[i] + " of Spades") ;
poker.deck.add(poker.cardTypes[i] + " of Hearts") ;
poker.deck.add(poker.cardTypes[i] + " of Clubs") ;
poker.deck.add(poker.cardTypes[i] + " of Diamonds") ;
}
Anyways, seems simple, right? Well, when I try to do that for all of the players, it crashes and gives me this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
This is my code:
static void dealOutHands() {
Poker poker = new Poker() ;
int pickedCard ;
for (int i = 0 ; i < 2 ; i++) {
pickedCard = (int) (Math.random() * poker.deck.size()) ;
poker.playerHand.add(poker.deck.get(pickedCard)) ;
poker.deck.remove(pickedCard) ;
}
for (int i = 0 ; i < 2 ; i++) {
pickedCard = (int) (Math.random() * poker.deck.size()) ;
poker.botHand1.add(poker.deck.get(pickedCard)) ;
poker.deck.remove(pickedCard) ;
}
for (int i = 0 ; i < 2 ; i++) {
pickedCard = (int) (Math.random() * poker.deck.size()) ;
poker.botHand2.add(poker.deck.get(pickedCard)) ;
poker.deck.remove(pickedCard) ;
}
for (int i = 0 ; i < 2 ; i++) {
pickedCard = (int) (Math.random() * poker.deck.size()) ;
poker.botHand3.add(poker.deck.get(pickedCard)) ;
poker.deck.remove(pickedCard) ;
}
for (int i = 0 ; i < 2 ; i++) {
pickedCard = (int) (Math.random() * poker.deck.size()) ;
poker.botHand4.add(poker.deck.get(pickedCard)) ;
poker.deck.remove(pickedCard) ;
}
}
For some reason, it keeps telling me that the error occurs here:
poker.playerHand.add(poker.deck.get(pickedCard)) ;
Can someone help? Thank you!