所以我试着学习Java,我编写了这段代码,假设从列表中生成单词组合,然后放在一个句子中。问题是第一个列表中随机选择的单词(名称)只包含名称,将被重用(我知道为什么,但我不确定我是否需要“phrase3”或第三个列表。
这是我的代码:
package ListOfWords;
public class test {
public static void main (String[] args) {
String[] name = {"Nicole","Ronnie","Robbie","Alex","Deb"};
String[] action = {"liar","driver","cook","speller","sleeper","cleaner","soccer
player"};
// find out how many words there are in each list
int nameLength = name.length;
int actionLength = action.length;
// Generate two random numbers
int rand1 = (int) (Math.random() * nameLength);
int rand2 = (int) (Math.random() * actionLength);
String phrase1 = name[rand1];
String phrase2 = action[rand2];
System.out.print("It is obvious that" + ' ' + phrase1 + " " + "is a better" + " " +
phrase2 + " " + "than" + " " + phrase1 + "!" );
}
}
这是我现在得到的结果:
It is obvious that Robbie is a better cleaner than Robbie!
因此,当您看到第一个列表中的随机名称被重用时 - 我如何确保它不会从第一个列表中选择相同的元素(名称)?
答案 0 :(得分:3)
您需要第三个随机数和短语,以选择要使用的第二个名称。例如:
// Generate two random numbers
int rand1 = (int) (Math.random() * nameLength);
int rand2 = (int) (Math.random() * actionLength);
int rand3 = (int) (Math.random() * nameLength);
String phrase1 = name[rand1];
String phrase2 = action[rand2];
String phrase3 = name[rand3];
System.out.print("It is obvious that" + ' ' + phrase1 + " " + "is a better" + " " +
phrase2 + " " + "than" + " " + phrase3 + "!" );
编辑: 为避免为phrase1和phrase3选择相同的名称,以下代码应确保使用不同的索引来选择phrase3而不是phrase1:
int rand1 = (int) (Math.random() * nameLength);
int rand2 = (int) (Math.random() * actionLength);
int rand3 = (int) (Math.random() * nameLength);
while(rand1==rand3){
rand3 = (int) (Math.random() * nameLength);
}
这将导致rand3被更改,直到它与rand1不同,后者将为phrase1和phrase3选择不同的名称。
请注意,如果names数组中只有一个名称,则会导致无限循环。
答案 1 :(得分:2)
你可以这样做:
List<String> randomNames = new ArrayList(Arrays.asList(name));
Collections.shuffle(randomNames);
int randAction = (int) (Math.random() * actionLength);
String phrase1 = randomNames.get(0);
String phrase2 = action[randAction];
String phrase3 = randomNames.get(1);
System.out.print("It is obvious that " + phrase1 + " is a better "
+ phrase2 + " than " + phrase3 + "!" );
答案 2 :(得分:1)
//Generate two random numbers
int rand1 = (int) (Math.random() * nameLength);
int rand2 = (int) (Math.random() * actionLength);
int rand3;
do{
rand3 = (int) (Math.random() * nameLength)
} while (rand3 == rand1);
String phrase1 = name[rand1];
String phrase2 = action[rand2];
String phrase3 = name[rand3];
System.out.print("It is obvious that" + ' ' + phrase1 + " " + "is a better" + " " +
phrase2 + " " + "than" + " " + phrase3 + "!" );
答案 3 :(得分:0)
例如,您似乎将随机初始化为4。然后,每次调用该索引时,您获得的值都相同。
在该结构中,您需要一个新变量。
如果你看一下编程的流程,你可以创建两个radom。然后设置它们。他们决不会重新初始化。
添加另一个变量来解决或创建一个函数来返回一个新的rand并将其传递给我而不是
看到你对第3阶段的评论可能是相同的。
来自下面的评论。 首先创建一个包含名称列表索引的数组。随机选择一个值。将此索引值替换为列表中的最后一个,并选择长度为1的另一个值。 - Jongware 27分钟前 。魔法。