I have already written simple random phrase generator. But I don't understand how to get rewrite this program using stringbuilder. I tried to use "append". but it just adds words into overall string.
My code:
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);
}
Like this:
String phrase = new StringBuilder(firstWord[rand1]).append(" ")
.append(secondWord[rand2]).append(" ")
.append(thirdWord[rand3]).append(" ")
.append(fourthWord[rand4]).toString();
Your example modified to use string builder. You can test it at https://www.tutorialspoint.com/compile_java8_online.php
import java.lang.StringBuilder;
public class HelloWorld{
public static void main(String []args){
String[] firstWord = {"one", "two","three"};
String[] secondWord = {"four", "five", "six"};
String[] thirdWord = {"seven", "eight", "nine"};
int oneLength = firstWord.length;
int secondLength = secondWord.length;
int thirdLength = thirdWord.length;
int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * secondLength);
int rand3 = (int) (Math.random() * thirdLength);
String phrase = firstWord[rand1] + " " + secondWord[rand2] + " "
+ thirdWord[rand3];
StringBuilder sb = new StringBuilder();
sb.append(firstWord[rand1]);
sb.append(" ");
sb.append(secondWord[rand2]);
sb.append(" ");
sb.append(thirdWord[rand3]);
String phraseSb = sb.toString();
System.out.println("Plus Operator: " + phrase);
System.out.println("String Builder: " + phraseSb);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.