Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random.choice Equivalent in Java for an Array

Here is an example of my random.choice implementation in Python.

available_cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Queen', 'King', 'Jack', 'Ace']
random_computer_card = random.choice(available_cards)
print random_computer_card

Just wondering what the Java equivalent would be for this piece of code. Obviously I haven't included the import statement in the sample.

Thanks in advance :)

like image 298
PythonBoy69 Avatar asked Dec 12 '22 02:12

PythonBoy69


1 Answers

Convert everything to String and define them in an array like below and access from index by generating random number:

String[] available_cards = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Queen", "King", "Jack", "Ace"};  
java.util.Random random = new java.util.Random();
int random_computer_card = random.nextInt(available_cards.length);
System.out.println(available_cards[random_computer_card]);
like image 116
SMA Avatar answered Dec 13 '22 17:12

SMA