如何随机选择枚举值?

时间:2016-02-08 19:00:28

标签: java random enums

我正在写一个二十一点游戏。我有一个所有可用卡类型的枚举。在交易时,我想使用随机从枚举中随机选择一张牌给玩家。如何使用整数值来对应枚举值?或者,如何为该枚举的变量随机选择枚举值?

void chooseCard() {
    Random rn = new Random();
    Card myCard = rn.nextInt(); //How can I do something like this? (randomly select Card value)? 0 being ACE, 1 being TWO...
}

卡片简称:

public enum Cards {
    ACE("ACE", 1, 11), TWO("TWO", 2), THREE("THREE", 3), FOUR("FOUR", 4), FIVE("FIVE", 5), SIX("SIX", 6), 
    SEVEN("SEVEN",7), EIGHT("EIGHT", 8), NINE("NINE", 9), TEN("TEN", 10), JACK("JACK", 10), KING("KING", 10), QUEEN("QUEEN",10);

    private int value1;
    private int value2;
    private String name;

    private Cards(String name, int value1) {
        this.value1 = value1;
    }

    private Cards(String name, int value1, int value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public int getValue1() {
        return value1;
    }

    public int[] getValue2() {
        int[] val = { value1, value2 };
        return val;
    }

    public String getName() {
        return name;
    }

}

1 个答案:

答案 0 :(得分:4)

// get an array of all the cards
private Card[]cards=Cards.values();
// this generates random numbers
private Random random = new Random();
// choose a card at random
final Card random(){
     return cards[random.nextInt(cards.length)];
}