0

I am writing code that is supposed to initialize a deck of cards, shuffle them, and then deal them to a specific number of players. I have written all the necessary methods, however when I try and implement them it compiles but when I run it I get a NullPointerException that's originating from my shuffle method.

What I'm thinking is that something is going wrong in my initialization of the deck of cards and thus when I try and access the deck in subsequent methods I'm getting the exception.

I'm just not sure what's going wrong and would be very grateful for some help! Here is the code:

(The exception appears when I attempt to switch the cards in the Shuffle method)

import java.util.Random;
import java.util.Arrays;

public class Deck
{


   private Card [] arrCards;

   public Deck()
   {
     Card [] arrCards = new Card[52];

     String [] suits = {"Hearts", "Spades", "Diamonds", "Clubs"};

     int count = 0;

     for(int i = 0; i < suits.length; i++)
     {
       for(int j = 1; j <= 13; j++)
       {

         Card deckCards = new Card(suits[i], j);

         deckCards.print();

         arrCards[count] = deckCards;

         count++;

       }


     }


   }

  public void shuffle()
  {

   int seed = 123;

   //create arbitrary new temp card

   Card temp = new Card("Hearts", 1);

   Random randNum = new Random(seed);


   for(int i = 0; i < 1000; i++)
   {

     int firstRand = randNum.nextInt(52);

     int secondRand = randNum.nextInt(52);


     temp = arrCards[firstRand];
     arrCards[firstRand] = arrCards[secondRand];
     arrCards[secondRand] = temp;

   }


 }

 public Card [] dealHand(int n, int playerNum)
 {

    Card [] playerCards = new Card[n];


    int counter = 0;

    int start = (n  * (playerNum - 1));

    int end = start + 12;

    for(int i = 0; i < n; i++)
    {
      for(int j = start; j < end; j++)
      {
       playerCards[i] = arrCards[j];

       }

     }

   return playerCards;
 }

}

Thank you so much I really appreciate it! (Especially since this is probably a really basic mistake somewhere)

:)

0 Answers0