java.util.Random Class:
java.util.Random class is used to generate random numbers. As we know random numbers are very useful especially in game development. In java we can generate random numbers in two ways either using java.lang.Math.random() method or by using methods of class java.util.Random.We import java.util.Random package to use Random class.
Example:
import java.util.Random;
public class RandomGenerator
{
public static void main(String args[])
{
Random ran1 = new Random(); // without seed
System.out.println("\t\tGenerating Random numbers without seed value");
for(int i = 0; i < 5; i++)
{
int k = ran1.nextInt();
System.out.print(k + "\t");
}
// with a seed of 100
Random ran2 = new Random(100);
System.out.println("\n\t\tGenerating Random numbers with a seed
value of 100");
for(int i = 0; i < 5; i++)
{
int k = ran2.nextInt();
System.out.print(k + "\t");
}
}
}
If two objects of Random
created with a same seed, and the same sequence of method calls is made for each, then they will generate and return common sequences of numbers.
0 Comment(s)