0

I'm learning Java and OOPS from oracle's website. I'm doing this exercise.

I'm getting a null pointer exception when I run this code. Can someone explain to me what I've done wrong?

Card.java

public class Card {
 public enum Suits {
    SPADE,
    CLUB,
    DIAMOND,
    HEART       
  }

 public enum Ranks {
    Ace,
    DEUCE,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN,
    EIGHT,
    NINE,
    TEN,
    JACK,
    QUEEN,
    KING    
  }

    public Ranks rank;
    public Suits suit;

    public Card(Card.Ranks rank,Card.Suits suit) {
        this.rank=rank;
        this.suit=suit;
    }
}

Deck.java

import java.util.*;

public class Deck {
    public ArrayList<Card> cards;
    private Card card;

    public Deck() {
        for(Card.Suits s: Card.Suits.values()) {
            for(Card.Ranks r:Card.Ranks.values()) {
                card=new Card(r,s);
                 cards.add(card);
            }
        }
    }
}

DisplayCards.java

public class DisplayCards {
    public static void main(String [] args) {
        Deck d=new Deck();
        for( Card c: d.cards) {
            System.out.println("Rank of the Card:"+c.rank.toString());
            System.out.println("Suit of the Card:"+c.suit.toString());  
        }
    }
}
4
  • 1
    Try pasting the stack trace from the exception into the question. This is usually the best way to start diagnosing such a problem. Commented Oct 13, 2011 at 14:40
  • It might speed up things if you said exactly were you get this NPE. Removing empty lines wouldn't hurt either. Commented Oct 13, 2011 at 14:40
  • I'm sorry for not putting up the exception. Commented Oct 13, 2011 at 15:15
  • Extremely silly of me to not being able to debug on my own. Thank you everyone for helping out so quick. Commented Oct 13, 2011 at 15:18

4 Answers 4

8

public ArrayList<Card> cards; is never initialized, use public ArrayList<Card> cards = new ArrayList<Card>();

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

Comments

4

you did not create the new ArrayList for cards.

replace: public ArrayList<Card> cards; with public ArrayList<Card> cards = new ArrayList<Card>();

Comments

4

You need to initialize the list as well:

cards = new ArrayList<Card>();

Comments

2

Now I'm coming from more of a C# background, but it doesn't look like you initialized your ArrayList Cards. Try initializing it in the constructor with:

cards = new ArrayList<Card>();

and that should fix your problem.

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.