从数组中打印随机字符串

时间:2017-11-20 03:56:17

标签: java

public static void main(String[] args) {

String word;
String[] RobinWords = {"Hole In A Donut", "Bankruptcy", "Popcorn", "Ravioli", "Hijack", "Camouflage", "Key Hole", "New Year's Eve", "Trampoline", "Zorro", "Hallucination", "Alter Ego", "Backfire", "Batman"};

Random rand = new Random();


word = RobinWords [rand.nextInt(RobinWords.length)];


System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");

}

看起来有点傻但我无法弄清楚如何使输出彼此不同。

3 个答案:

答案 0 :(得分:1)

你可能想做什么

for (int i = 0 ; i < 5 ; i++)
{
  word = RobinWords[rand.nextInt()]; 
  System.out.println("Holy " + word + ", Batman");
}

此代码将选择一个随机索引,将其发送到您的数组,将该索引的相应元素存储在String中,然后打印该字符串。

答案 1 :(得分:0)

将它放在循环中,并在每次迭代时获得一个新的随机字。

String[] robinWords = { "Hole In A Donut", "Bankruptcy", "Popcorn", "Ravioli", //
        "Hijack", "Camouflage", "Key Hole", "New Year's Eve", "Trampoline", //
        "Zorro", "Hallucination", "Alter Ego", "Backfire", "Batman" };

Random rand = new Random();
for (int i = 0; i < 5; i++) {
    int index = rand.nextInt(robinWords.length);
    System.out.printf("Holy %s, Batman!%n", robinWords[index]);
}

请注意,我尝试使用robinWords的更标准名称并使用printf代替String连接来提高代码的可读性。如果您需要五个独特的短语,那么您可能更喜欢Set;假设您使用Java 8+,您可以执行类似

的操作
Set<String> wordSet = new LinkedHashSet<>();
Random rand = new Random();
while (wordSet.size() < 5) {
    int index = rand.nextInt(robinWords.length);
    wordSet.add(robinWords[index]);
}
wordSet.stream().forEachOrdered(word -> 
        System.out.printf("Holy %s, Batman!%n", word));

答案 2 :(得分:0)

试试这个

System.out.println("Holy " +  RobinWords [rand.nextInt(RobinWords.length)] + ", Batman!");

因为rand.nextInt()执行时只生成一次随机数