Java Program to Print Random Words


Posted on 12 January 2017

In this tutorial, we will learn how to print random words using Java, we are going to use the rand() method of Math Class, rand() returns a double number ranging from 0 .0 to 1.0.

Let us see the java code to print random numbers from a given set of array

Java program to print random words

public class RandomPhrase{
 public static void main(String[] args){//start main
//random words
  String[] WordsOne = {"six sigma", "multi-tier”, “paradigm", "win-win", 
"end", "mind", "What"};
  String[] WordsTwo = {"sticky", "oriented", "stupid", "noob"};
  String[] WordsThree = {"noob", "gg-ez", "kids", "spammer", "astroA50"};
  String[] wordFour = {"ok", "done", "fine" , "games"};

//finding how many words in String
int oneLength = WordsOne.length;
int twoLength = WordsTwo.length;
int threeLength = WordsThree.length;
int fourLength = wordFour.length;

//random numbers
int ran1=(int) (Math.random() *oneLength); 
int ran2=(int) (Math.random() *twoLength);
int ran3=(int) (Math.random() *threeLength);
int ran4=(int) (Math.random() *fourLength);

//building random Phrase
String phrase = WordsOne[ran1]+" "+WordsTwo[ran2] + " " + WordsThree[ran3]+" " + wordFour[ran4];

System.out.println(phrase+" is imaginary");
}//end main
}//end class

How it works.

In short - The program makes three lists of words, then randomly picks one word from each of the three lists and prints out the result.

  1. We first assign 4 String sets some random set of words. String[] positions = { “One”, “Two”, “Three” }
  2. Next we find the length of the String by method length, i.e. How many words are there in the String.
  3. A Random number is then selected by help of method Random() present in class Math. This method returns a random int value between 0 and 1, but not 1. We multiply this random number by the length of the List of Words, and then it is type casted to int to remove the values after decimal point. Ex: int x = (int) 3.14; stores 3
  4. Now we build the sentence by picking words from the String by the random numbers generated above, we use the ‘+’ concatenation operator to join the two Strings together.
  5. Finally We print the phrase.


Random Phrase in Java

Thank you for reading

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.

If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts