Sunday, October 14, 2012

Use "random" method in Java !



The below program show you the use of random.



public class Random{

public static void main(String[] args) {


String[] wordone = {"lucy", "suzy", "john"};


String[] wordtwo = {"is","can be","could be","like to"};


String[] wordthree = {"lucky", "beautiful", "handsome" ,"and whatever", "teacher", "engineer"};


int sample1 = wordone.length;

int sample2 = wordtwo.length;
int sample3 = wordthree.length;

int rand1 = (int) (Math.random() * sample1);

int rand2 = (int) (Math.random() * sample2);
int rand3 = (int) (Math.random() * sample3);


String word = wordone[rand1] +" "+ wordtwo[rand2] +" "+ wordthree[rand3];


System.out.println(word);


}

}
______________________________________________________________________
Output:


lucy is lucky
______________________________________________________________________


This is small program to learn use of random and easy logic that any beginner can learn it.

In this program "wordone.length" means it count each word that is three here and it could be more than that, you can add as many as you like.


Now for example "(int) (Math.random()*3" this means randomly integer between 0 to 2. If it is  "(int) (Math.random()*6" than it should be 0 to 5.


We make "String word" to combine the result of each String in one that is "word".


Each time you run this program, you will find different result as it change as per randomly chosen word.


You can copy and paste this code but if you start write this code manually than, it really help you to remember this methods. Try it on your own than tell me the difference !

Thank you for viewing this post.........

No comments:

Post a Comment