无法弄清楚为什么我得到这个NullPointerException

时间:2014-07-14 06:10:17

标签: java nullpointerexception

我正在尝试制作纸牌游戏。它有3个类,“PlayingCard”,“DeckOfPlayingCards”和“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());
    }
}

一切都编译得很好,但是当我运行它时,我在线程“main”java.lang.NullPointerException at DeckOfPlayingCards.<init>(DeckOfPlayingCards.java:11) at Game.main(Game.java:6)

中得到一个例外

据我所知,当我尝试访问null的内容时会抛出此异常。我简化了程序以查看问题所在,但我仍然无法弄明白。我在调用之前初始化了2个元素的数组,所以我不知道出了什么问题。请帮帮我

1 个答案:

答案 0 :(得分:1)

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

意味着你初始化了一组但尚未初始化的元素

所以将它们初始化为

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

deck[0].setRankAndSuit("1","S");