无法找到空指针异常

时间:2018-10-19 08:54:30

标签: java nullpointerexception

该类的最后一行出现错误,我试图在该行中打印卡组中第一张卡片的编号,但我不确定为什么。

    public class CardTricks {
    public static void main (String[] args){

        Deck newdeck = new Deck();
        newdeck.construct();
        newdeck.shuffle();
        System.out.println(newdeck.deck[0].Number);

    }
}

这是卡片的类,其主要目的是为卡片提供套件属性和数字属性。

public class Card {
    String Suite;
    int Number;
}

这是牌组类,该类中的函数用于创建牌组并对其进行随机播放。

public class Deck {
    Card[] deck;

    public void construct(){

        deck = new Card[52];

        String[] possuite = new String[4];
        possuite[0] = "Hearts";
        possuite[1] = "Diamonds";
        possuite[2] = "Clubs";
        possuite[3] = "Spades";

        int x = 0;

        while (x < 4){
            String suite = possuite[x];
            x++;
            int number = 1;
            System.out.println(suite);

            while (number < 14){
                deck[number-1] = new Card();

                deck[number-1].Suite = suite;
                deck[number-1].Number = number;
                number++;
           }
        }
    }

    public void shuffle(){
        int x;
        int y;
        int z = 0;

        while (z < 10000){
            x = (int)(Math.random()*52);
            y = (int)(Math.random()*52);
            Card a = deck[y];
            Card b = deck[x];
            deck[x] = a;
            deck[y] = b;
            z++;
        }

    }
}

2 个答案:

答案 0 :(得分:1)

您只填充甲板上的前13个位置,并且每次生成新套件时都将其覆盖。

您应该做什么:(请注意,我已将x++移至底部)

    while (x < 4){
        String suite = possuite[x];
        int number = 1;
        System.out.println(suite);

        while (number < 14){
            int cardPos = (number-1) + (13*x);
            deck[cardPos] = new Card();


            deck[cardPos].Suite = suite;
            deck[cardPos].Number = number;
            number++;
       }
       x++;

答案 1 :(得分:0)

newdeck.deck[0]之所以为null,是因为在仅初始化元素0到12时,您对所有52个字段元素进行了混洗。

随机播放将null元素放置在deck[0]位置。

// this creates a new array with elements 0 to 51 == null
deck = new Card[52];