The class Java.util.Random in the Java Utility Class Library provides a way to generate random numbers of various types. It can produce random numbers of types such as int, long, float, double, and Goussian. This is the biggest difference between it and the method random () in Java.lang.Math, which only produces a double random number.
The method in class random is very simple, it has only two constructs and six common methods.
Construction Method:
(1) public Random ()
(2) Public Random (long Seed)
Java generates random numbers need to have a base value seed, in the first method the base value defaults, then the system time as seed.
Common method:
(1) Public synonronized void Setseed (Long Seed)
The method is to set the base value seed.
(2) public int nextint ()
The method is to produce an integer random number.
(3) public long Nextlong ()
The method is to produce a long random number.
(4) Public float nextfloat ()
The method is to produce a float-type random number.
(5) public double nextdouble ()
The method is to produce a double random number.
(6) Public synchronized double Nextgoussian ()
The method is to produce a double type of Goussian random number.
Example 2 Randomapp.java.
Import java.lang.*;
Import Java.util.Random;
public class randomapp{
public static void Main (String args[]) {
Random ran1=new Random ();
Random ran2=new Random (12345);
An object with two class random was created.
System.out.println ("The 1st set of random numbers:");
System.out.println ("Integer:" +ran1.nextint ());
System.out.println ("Long:" +ran1.nextlong ());
System.out.println ("Float:" +ran1.nextfloat ());
System.out.println ("Double:" +ran1.nextdouble ());
System.out.println ("Gaussian:" +ran1.nextgaussian ());
Generate random numbers of various types
System.out.print ("The 2nd set of random numbers:");
for (int i=0;i<5;i++) {
System.out.println (Ran2.nextint () + "");
if (i==2) System.out.println ();
produces different random numbers of the same type.
System.out.println ();
}
}
}
Random random=new Random ();
Random.nextint ();