Java Reference
In-Depth Information
88 2
110 3
97 4
99 5
109 6
82 7
116 8
99 9
114 10
$
The next step is to run these through a statistical program to see how really random they are;
we'll return to this in a minute.
In general, to generate random numbers, you need to construct a java.util.Random object
(not just any old random object) and call its next*() methods. These methods include nex-
tBoolean() , nextBytes() (which fills the given array of bytes with random values), nex-
tDouble() , nextFloat() , nextInt() , and nextLong() . Don't be confused by the capitaliz-
ation of Float , Double , etc. They return the primitive types boolean , float , double , etc.,
not the capitalized wrapper objects. Clear enough? Maybe an example will help:
// java.util.Random methods are non-static, so need to construct
Random r = new
new Random ();
for
for ( int
int i = 0 ; i < 10 ; i ++)
System . out . println ( "A double from java.util.Random is " + r . nextDouble ());
for
for ( int
int i = 0 ; i < 10 ; i ++)
System . out . println ( "An integer from java.util.Random is " + r . nextInt ());
You can also use the java.util.Random nextGaussian() method, as shown next. The
nextDouble() methods try to give a “flat” distribution between 0 and 1.0, in which each
value has an equal chance of being selected. A Gaussian or normal distribution is a bell-
curve of values from negative infinity to positive infinity, with the majority of the values
around zero (0.0).
// Random3.java
Random r = new
new Random ();
for
for ( int
int i = 0 ; i < 10 ; i ++)
System . out . println ( "A gaussian random double is " + r . nextGaussian ());
Search WWH ::




Custom Search