试图从数组中获取随机元素

时间:2013-10-10 19:49:45

标签: java random

我要做的是制作一个卡片类,通过随机生成一个值和一套西装来随机生成一张卡片。我不在乎它是否创造了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”。上面的代码是错误的吗?或者是我必须在手工课上误入歧途?

2 个答案:

答案 0 :(得分:0)

您将PostCards的长度作为Pos Suits随机数的限制

你正在做的事情:

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)];

答案 1 :(得分:-4)

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

然后你切换了卡片和套装的.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;
    }
}