0

我想做的是制作一个卡片类,它会通过随机生成一个值和一套花色来随机生成一张卡片。我不在乎它是否会创建 4 张完全相同的卡片,这对我来说不是问题。但以下是我认为迄今为止我最好的尝试。

String[] PossCards = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
String[] PossSuits = new String[]{"C", "S", "H", "D"};
Random rand = new Random();

public Card(){

    String Card = PossCards[rand.nextInt(PossCards.length)];
    String Suit = PossSuits[rand.nextInt(PossSuits.length)]; 

    String ActCard = Suit + "" + Card;
}

但这不起作用,当我使用 Hand 类尝试创建 4 张随机卡片时,返回的值是“null null null null”。是上面代码的错误吗?或者这是我在手课上必须弄错的东西?

4

2 回答 2

0

您将 PossCards 的长度作为 PossSuits 随机数的限制

你正在做:

String Suit = PossCards[rand.nextInt(PossSuits.length)];
String Card = PossSuits[rand.nextInt(PossCards.length)];

你应该这样做:

String Card = PossCards[rand.nextInt(PossCards.length)];
String Suit = PossSuits[rand.nextInt(PossSuits.length)];
于 2013-10-10T20:10:32.573 回答
-4

首先是 java 的命名约定——变量和方法使用小写字符。

然后你切换了 Cards and Suits 的 .length 方法,所以你应该有这个:

String Suit = PossCards[rand.nextInt(PossCards.length)];
String Card = PossSuits[rand.nextInt(PossSuits.length)]; 

工作示例看起来像这样(不知道,为什么您的示例不起作用 - 可能错误出现在您没有与我们共享的代码中):

public class JavaApplication8 {

    public static String[] possCards = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
    public static String[] possSuits = new String[]{"C", "S", "H", "D"};
    public static Random rand = new Random();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        while (1<2){
            System.out.println(card());
        }
    }

    public static String card() {
        String suit = possSuits[rand.nextInt(possSuits.length)];
        String card = possCards[rand.nextInt(possCards.length)];

        return suit + card;
    }
}
于 2013-10-10T19:52:09.790 回答