-2

I am taking AP Comp Sci and working on the lab "elevens". All I'm trying to do is instantiate an object of the "Deck" class, and my constructor is throwing a NullPointerError. After doing a print check, I found that the first index is being found correctly, it's the second that's throwing the error. What do I need to change in either my Deck class or my main method to fix this issue?

public Card(String cardRank, String cardSuit, int cardPointValue) 
{
    suit = cardSuit;
    rank = cardRank;
    pointValue = cardPointValue;
}

private ArrayList<Card> cards;

public Deck(String[] ranks, String[] suits, int[] values) 
{
    for(int i =0; i < suits.length; i++)
    {                
        cards.add(new Card(ranks[i], suits[i], values[i]));
        size++;
    }
}

public static void main(String[] args) 
{
    String [] suits = new String [] {"Spades", "Hearts", "Diamonds"};
    String [] ranks = new String [] {"Queen", "King", "Ace"};
    int [] points = new int [] {10, 10, 11};
    Deck deck = new Deck(ranks, suits, points);
}
Andrew Regan
  • 5,087
  • 6
  • 37
  • 73

2 Answers2

3

When you say private ArrayList<Card> cards;, it is equivalent to

private ArrayList<Card> cards = null;

which is why cards is null in your constructor. Change it to something like1

private List<Card> cards = new ArrayList<>();

Or, add a cards = new ArrayList<>(); before your for loop (in your constructor).

Also, you appear to be missing both clubs and jacks

String [] suits = {"Clubs", "Spades", "Hearts", "Diamonds"};
String [] ranks = {"Jack", "Queen", "King", "Ace"};

1And prefer programming to the List interface.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Why do you keep answering these garbage questions? I'll never understand you. – Savior Apr 13 '16 at 22:54
  • 2
    @Pillar Because programming is **hard** and I remember being young and I have empathy for the asker. You may think the question is unworthy of your time, but we all started somewhere. – Elliott Frisch Apr 13 '16 at 22:56
  • I'm not against commenting the answer to help them out, but more of these questions and answers have no purpose being here. – Savior Apr 13 '16 at 22:57
  • 1
    _Garbage question_ might be harsh. My point is that the duplicate already explains all this and more. – Savior Apr 13 '16 at 23:00
  • Thank you! I apologize for the repetition; I created a new question because I didn't understand originally where the error was coming from as the line of code that gets highlighted from the compiler is the line where I add the card, not the actual initialization of the array. – CSiamof Apr 14 '16 at 01:15
2

cards hasn't been instantiated, so it is still null, and will cause a NPE when you try to interact with it.

Simplest solution (given that we should minimise the prevalence of nulls in our code):

private ArrayList<Card> cards = new ArrayList<>();
Andrew Regan
  • 5,087
  • 6
  • 37
  • 73