Reputation: 17
I have been trying to create a deck of cards using this code:
public DeckOfCards()
{
//constructor fills deck of Cards
String faces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve" };
String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
deck = new Cards[ NUMBER_OF_CARDS ];
currentCard = 0;
randomNumbers = new Random();
//populate deck with Card objects
for( int count = 0; count < deck.length; count++ )
deck[ count ] =
new Cards( faces[ count % 13 ], suits[ count / 13 ] );
} //end DeckOfCard constructor
Yet, there is one error that I just cannot fix. It pops out like this: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at:
for( int count = 0; count < deck.length; count++ )
deck[ count ] =
new Cards( faces[ count % 13 ], suits[ count / 13 ] );
Why does this error keep showing up? Any help will be greatly appreciated.
Upvotes: 1
Views: 212
Reputation: 3767
You're missing a card (Thirteen/King) in your faces[]
array. Right now count % 13
will give you an array out of bounds error
when it returns 12 because your array only has 12 elements [0-11]. Either add a Thirteen
to your faces
array or reduce your modulus value from 13 to 12.
Upvotes: 1