我的程序旨在从一副纸牌中随机抽取5张纸牌。但是,当我运行它时,输出为:


  null null null null null


public class Poker {
    static int numberOfPlayers;

    public static void main(String[] args) {
        drawComCards();
    }

    static void drawComCards() {
        Card[] comCard = new Card[5];
        for (int i = 0; i < comCard.length; i++)
            comCard[i] = new Card();

        for (int i = 0; i < comCard.length; i++)
            System.out.print(comCard[i].getCard() + "  ");
    }
}

public class Card {
    private String[] rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
    private String[] suit = {"clubs", "diamonds", "hearts", "spades"};
    private String cardValue;

    void Card() {
        String cardOne = rank[(int) (Math.random() * rank.length)] + " of " + suit[(int) (Math.random() * suit.length)];
        cardValue = cardOne;
    }

    String getCard() {
        return cardValue;
    }
}


我还没有想过如何消除多次绘制同一张卡片的想法。

最佳答案

由于这一行:

void Card(){..}


删除void。这段代码表示方法(构造方法不描述返回类型-即使使用void也是如此)。因此,编译器添加了默认的无参数构造函数,该构造函数使用cardValue初始化null

10-01 08:37