2017-03-04 107 views
1

我已经写了简单的随机短语生成器。但我不明白如何使用stringbuilder重写这个程序。我试图使用“追加”。但它只是将单词添加到整个字符串中。如何使用java 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); 
} 
+2

测试它仅供参考,'fourthWord'不存在于上述共享的代码。 – nullpointer

+2

您能否提供一个不适合您的StringBuilder示例。 –

+0

好吧,我已经纠正这 – Alex

回答

2

像这样:

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

谢谢。但为什么你使用.toString方法? – Alex

+1

需要将'StringBuilder'转换为'String',它们是不同的类型。尝试删除'toString()' - 它不会编译。 –

1

你举的例子修改为使用字符串生成器。可以在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); 

    } 
}