gpt4 book ai didi

java - 如何使用 java stringbuilder 创建一个随机短语?

转载 作者:行者123 更新时间:2023-11-29 04:33:55 27 4
gpt4 key购买 nike

我已经编写了简单的随机短语生成器。但我不明白如何使用 stringbuilder 重写这个程序。我尝试使用“追加”。但它只是将单词添加到整个字符串中。

我的代码:

public static void main(String[] args){
String[] firstWord = {"one", "two","three"};
String[] secondWord = {"four", "five", "six"};
String[] thirdWord = {"seven", "eight", "nine"};
String[] fourthWord = {"ten", "eleven", "twelve"};

int oneLength = firstWord.length;
int secondLength = secondWord.length;
int thirdLength = thirdWord.length;
int fourthLength = fourthWord.length;

int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * secondLength);
int rand3 = (int) (Math.random() * thirdLength);
int rand4 = (int) (Math.random() * fourthLength);

String phrase = firstWord[rand1] + " " + secondWord[rand2] + " "
+ thirdWord[rand3] + fourthWord[rand4];
System.out.println(phrase);
}

最佳答案

像这样:

String phrase = new StringBuilder(firstWord[rand1]).append(" ")
.append(secondWord[rand2]).append(" ")
.append(thirdWord[rand3]).append(" ")
.append(fourthWord[rand4]).toString();

关于java - 如何使用 java stringbuilder 创建一个随机短语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599419/

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