1

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.

1
  • 1
    You don't have King in faces array. And why are you naming Eleven instead of Jack? Commented Mar 15, 2015 at 15:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.