如何从列表中选择随机字符串

时间:2015-10-14 13:34:44

标签: java string random

我正在尝试创建一个程序来刺激从牌组中挑选一张牌。我曾尝试使用Random类来挑选suitrank,但我无法让它发挥作用。到目前为止,这是我的代码。

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

我确信这很简单,但我对Java相对较新,所以对任何帮助表示赞赏!

4 个答案:

答案 0 :(得分:3)

你做得对。您只需要打印正确的变量:

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

答案 1 :(得分:1)

问题在于:System.out.println("The card you picked is " + Arrays.toString(rank) + " of " + Arrays.toString(suit));。您每次都打印完整的项目列表。

您需要做的是将(rank[idx])(suit[idx]);放入字符串变量并打印出来。

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

答案 2 :(得分:0)

请务必添加错误,但未包含您遇到的问题。

但我期待以下情况:

1)字符串随机声明两次 2)不需要Arrays.toString()

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

为什么使用Arrays.ToString()?

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

答案 3 :(得分:0)

您正在重复变量名称idxrandom,选择不同的名称并输出如下:

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

Live Java示例:

http://ideone.com/9asht6