Ashwin Gupta February 2016

How to randomly select an enum value?

I'm writing a game of Blackjack. I have an enum of all available card types. When dealing, I want to use Random to randomly select a card from the enum to give to the player. How can I use an integer value to correspond to an Enum Value? Or, how can I randomly select an enum value for an variable of that enum?

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...
}

Enun of Cards:

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;
    }

}

Answers


emory February 2016

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

Post Status

Asked in February 2016
Viewed 2,737 times
Voted 4
Answered 1 times

Search




Leave an answer