它一直在说java.lang.nullpointerexception。试图找出是什么。帮助任何人?

时间:2014-12-05 15:42:09

标签: arrays nullpointerexception

一直想弄清楚代码有什么问题。有什么我不能做对的吗?

public class deck2 {     公共卡[]甲板;

public void CreateDeck() {
    String[] suit = { "Spades", "Hearts", "Diamonds", "Clubs" };//Array for suit
    int[] number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; // Array for rank

    for (int i = 0; i <suit.length ; i++) {//Looping the suit array
        for (int n = 0; n < number.length; n++) { // Looping the number array
            Card c = new Card(suit[i], number[i]); //Calling the constructor from my card class
            if (deck[i] == null) {
                deck[i] = c;


            }

        }

    }

}

public void displayDeck() {
    for (int i = 0; i <deck.length; i++) {
        if (deck[i] != null) {
            deck[i].display(); // Calling the display method from my card class. 
        }
    }

}

}

1 个答案:

答案 0 :(得分:0)

我猜你的套牌是空的。

public class deck2 { 

public Card[] deck;  // deck is null

public deck2() {
   deck = new Card[52]; // now it's not.
}

public void CreateDeck() {
    String[] suit = { "Spades", "Hearts", "Diamonds", "Clubs" };//Array for suit
    int[] number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; // Array for rank

    for (int i = 0; i <suit.length ; i++) {//Looping the suit array
        for (int n = 0; n < number.length; n++) { // Looping the number array
            Card c = new Card(suit[i], number[i]); //Calling the constructor from my card class
            if (deck[i] == null) {
                deck[i] = c;
            }
        }
    }
}

这段代码还不错。你最终只会得到13张牌,而不是52张牌:所有俱乐部。 (你知道为什么吗?)