HOW TO RANDOM.CHOICE EQUIVALENT IN JAVA FOR AN ARRAY?

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
 1115  View(s)
Ratings:
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.

  1. Barbara Jones

    Post:13

    Points:91
    Re: How to Random.choice Equivalent in Java for an Array?

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!