Search code examples
javatostringshuffle

Java ArrayIndexOutOfBoundsException When Trying to Test


I seem to be getting an error with my deck of cards project. I'm trying to print out a shuffled deck of cards and I've had help already, but this error is now stopping me from progressing

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 51
	at Pack.<init>(Pack.java:14)
	at PackTester.main(PackTester.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)

  public class Pack {

private PlayingCard[] deck;   // An array of 52 cards, representing the deck.
private int cardsUsed; // How many cards have been dealt from the deck.

/**
* Creating an unshuffled deck of cards
*/
public Pack() {
   deck = new PlayingCard[51]; //Creates an array of 52 playing cards
   int cardCt = 0; // How many cards have been created so far.
   for ( int suit = 0; suit <= 3; suit++ ) { //If a suit is complete, move to the next suit
      for ( int rank = 1; rank <= 14; rank++ ) { //Builds a complete suit
         deck[51] = new PlayingCard(rank, suit);
         cardCt++; //Adds one to the card count
      }
   }
   cardCt = 0;
}

/**
* Shuffling a deck of cards
*/
public void shuffle() {
      // Put all the used cards back into the deck, and shuffle it into
      // a random order.
    for ( int i = 51; i > 0; i-- ) { 
        int rand = (int)(Math.random()*(i+1));
        PlayingCard temp = deck[i];
        deck[i] = deck[rand];
        deck[rand] = temp;
    }
    cardsUsed = 0;
}

public @Override String toString() {

String deckStr = "";

for (int i=0; i<52; i++) {
    deckStr = deckStr + deck[i].toString() + " ";
}

return deckStr;
}
} // end class Pack

And here is the tester class.

public class PackTester {

public static void main(String[] args)
{
    Pack myPack = new Pack();
    myPack.shuffle();
    System.out.println(myPack.toString());
}
}

I just don't know where to go from here so any help would be appreciated.


Solution

  • In order to create a Deck of 52 cards you need :

    deck = new PlayingCard[52];
    

    In addition, it makes little sense for your loop to always assign a card to the 51st position :

    deck[51] = new PlayingCard(rank, suit);
    

    This would make more sense :

    public Pack() {
       deck = new PlayingCard[52]; //Creates an array of 52 playing cards
       int cardCt = 0; // How many cards have been created so far.
       for ( int suit = 0; suit <= 3; suit++ ) { //If a suit is complete, move to the next suit
          for ( int rank = 1; rank < 14; rank++ ) { //Builds a complete suit
             deck[cardCt] = new PlayingCard(rank, suit);
             cardCt++; //Adds one to the card count
          }
       }
    }
    

    Also note that there should be 13 ranks, not 14.