Java Reference
In-Depth Information
Solution
Use
java.lang.Math.random()
to generate random numbers. There is no claim that the
random values it returns are very
good
random numbers, however. This code exercises the
random()
method:
// Random1.java
// java.lang.Math.random( ) is static, don't need any constructor calls
System
.
out
.
println
(
"A random from java.lang.Math is "
+
Math
.
random
( ));
Note that this method only generates double values. If you need integers, construct a
java.util.Random
object and call its
nextInt()
method; if you pass it an integer value,
this will become the upper bound. Here I generate integers from 1 to 10:
public
public class
class
RandomInt
RandomInt
{
public
public static
void
main
(
String
[]
a
) {
Random r
=
new
static
void
new
Random
();
for
for
(
int
int
i
=
0
;
i
<
1000
;
i
++)
// nextInt(10) goes from 0-9; add 1 for 1-10;
System
.
out
.
println
(
1
+
r
.
nextInt
(
10
));
}
}
To see if my
RandomInt
demo was really working well, I used the Unix tools
sort
and
uniq
,
which together give a count of how many times each value was chosen. For 1,000 integers,
each of 10 values should be chosen about 100 times. I ran it twice to get a better idea of the
distribution.
$
java numbers.RandomInt | sort | uniq -c | sort -k 2 -n
96 1
107 2
102 3
122 4
99 5
105 6
97 7
96 8
79 9
97 10
$
java -cp build numbers.RandomInt | sort | uniq -c | sort -k 2 -n
86 1