gpt4 book ai didi

java - 带有列表中单词的句子生成器

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:48:37 24 4
gpt4 key购买 nike

所以我正在尝试学习 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!

当您看到第一个列表中的随机名称被重用时 - 我如何确保它不会从第一个列表中选择相同的元素(名称)?

最佳答案

您需要第三个随机数和短语,以选择要使用的第二个名字。例如:

// 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 选择相同名称的可能性,以下代码应确保使用与 phrase1 不同的索引来选择 phrase3:

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选择不同的名字。

请注意,如果名称数组中只有一个名称,这将导致无限循环。

关于java - 带有列表中单词的句子生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17903406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com