1

I'm trying to create a card game. It has 3 classes, "PlayingCard", "DeckOfPlayingCards" and "Game".

public class PlayingCard {

    private String rank;
    private String suit;

    public void setRankAndSuit(String rank, String suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public String getRankAndSuit() {
        return rank + " of " + suit;
    }
}

public class DeckOfPlayingCards extends PlayingCard {

    // Array of playing card objects
    static PlayingCard[] deck = new PlayingCard[2];

    DeckOfPlayingCards() { // This is my line 11 BTW
        deck[0].setRankAndSuit("1", "S");
        deck[1].setRankAndSuit("2", "S");
    }
}

public class Game extends DeckOfPlayingCards {

    public static void main(String[] args) {

        DeckOfPlayingCards newDeck = new DeckOfPlayingCards(); // This is my
        // line 6
        System.out.println(deck[0].getRankAndSuit());
    }
}

Everything compiles fine, but when I run it, I get a Exception in thread "main" java.lang.NullPointerException at DeckOfPlayingCards.<init>(DeckOfPlayingCards.java:11) at Game.main(Game.java:6)

As I understand, this exception is thrown when I'm trying to access something which is null. I simplified the program to see where the problem is, but I still can't figure it out. I initialized the array of 2 elements before I called them, so I don't know what is wrong. Please help me

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
n.k
  • 21
  • 5
  • Of particular note: [this answer](http://stackoverflow.com/a/23852556/1079354) in that question covers your exact issue; you're dereferencing something in an array before initializing it. – Makoto Jul 14 '14 at 06:12

1 Answers1

1
static PlayingCard [] deck = new PlayingCard[2];

means you initialized an array of but elements haven't been initialized yet

so initialize them like

deck[0] = new PlayingCard();
deck[1] = new PlayingCard();

deck[0].setRankAndSuit("1","S");
jmj
  • 237,923
  • 42
  • 401
  • 438