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!");
}
看起来有点傻但我无法弄清楚如何使输出彼此不同。
答案 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()
执行时只生成一次随机数