0

So I'm trying to test to see if my deckOfCards Array is going to print out properly. Here is the code

public class Deck {
    private static final String face[] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", 
                                            "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
    private static final String suit[] = {"Spade", "Club", "Diamond", "Heart"};
    private static final Card deckOfCards[] = new Card [52];

    public Deck(){
        int suitCount = 0;
        int faceCount = 0;
        int faceValue = 0;
        for(int i = 1; i < deckOfCards.length; i++){
            deckOfCards[i].setSuit(suit[suitCount]);
            deckOfCards[i].setFace(face[faceCount], faceValue);
            suitCount++;
            faceCount++;
            faceValue++;
            if(suitCount == 3){
                suitCount = 0;
            }
            if(faceCount == 12){
                faceCount = 0;
            }
            if(faceValue == 13){
                faceValue = 1;
            }
        }
    }

As you can see I've defined the face and suit in an array, and I want to assign them to their proper value, however when I try to run it, I get a nullPointerException at the line deckOfCards[i].setSuit(suit[suitCount]);

I cannot seem to figure out why it giving me this error, when I debug it, it seems to initialize all the fields, yet when it gets there it crashes.

1 Answers1

2

You initialize the array, but not the elements in it. You can do that in the loop:

deckOfCards[i] = new Card();
deckOfCards[i].setSuit(suit[suitCount]);
C. L.
  • 571
  • 1
  • 8
  • 26