Home > DeveloperSection > Forums > How to Random.choice Equivalent in Java for an Array?
Pravesh Singh

Total Post:411

Points:2881
Posted on    November-04-2014 10:47 PM

 Java Python-3.4  Netbeans 
Ratings:


 1 Reply(s)
 746  View(s)
Rate this:

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

available_cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'TeamLeader', 'Rohit', 'Kesharwani', 'Alld']
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.



Barbara Jones

Total Post:13

Points:91
Posted on    November-04-2014 11:50 PM

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", "TeamLeader", "Rohit", "Kesharwani", "Alld"}; 

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


Don't want to miss updates? Please click the below button!

Follow MindStick