简体   繁体   中英

How to select a random string from a list

I'm trying to create a program which stimulates picking a card from a deck. I've tried to use the Random class to pick the suit and the rank but I can't get it working. This is my code so far.

   String[] rank = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10",  "Jack", "Queen", "King"};
   int idx = new Random().nextInt(rank.length);
   String random = (rank[idx]);

   String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"};
   int idx = new Random().nextInt(suit.length);
   String random = (suit[idx]);

   System.out.println("The card you picked is " + Arrays.toString(rank) + " of " + Arrays.toString(suit));

I'm sure it's very simple but I'm relatively new to Java so any help is appreciated!

You did it correctly. You just need to print the right variables:

String[] rank =  // ...
int rankIndex = new Random().nextInt(rank.length);
String randomRank = rank[rankIndex];

String[] suit = // ...
int suitIndex = new Random().nextInt(suit.length);
String randomSuit = suit[suitIndex];

System.out.println("The card you picked is " + randomRank + " of " + randomSuit);

The problem is here: System.out.println("The card you picked is " + Arrays.toString(rank) + " of " + Arrays.toString(suit)); . You are printing your complete list of items each time.

What you need to do is to place (rank[idx]) and (suit[idx]); into string variables and print those.

    String[] rank = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
    int idx = new Random().nextInt(rank.length);
    String randomRank = (rank[idx]);

    String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"};
    idx = new Random().nextInt(suit.length);
    String randomSuit = (suit[idx]);
    System.out.println("The card you picked is " + randomRank + " of " + randomSuit);

Please be sure to add what's wrong, you haven't included what problem you are having.

But I'm expecting it's the following:

1) String random is declared twice 2) Arrays.toString() is not needed

System.out.println("The card you picked is " + **Arrays.toString(rank)** + " of " + Arrays.toString(suit));

Why are you using Arrays.ToString()?

 String rankstr = (rank[idx]);
 String suitStr = (suit[idx]);
    System.out.println("The card you picked is " + rankStr + " of " + suitStr);

You're repeating the variables names idx and random , choose different names and output like this:

System.out.println("The card you picked is " +random2+ " of " +random);
//The card you picked is 2 of Spades

Live Java Example:

http://ideone.com/9asht6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM