samedi 4 mars 2017

How to create a random phrase using java stringbuilder?

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"};

    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);
}




Aucun commentaire:

Enregistrer un commentaire