HelloRandom
//
// HelloRandom.java
//
public class HelloRandom
{
public static void main(String[] args)
{
// Math.random() returns a double in [0,1)
System.out.println("Random doubles in [0,1):");
for (int i=0; i<5; i++)
{
double value = Math.random();
System.out.println(value);
}
// Multiplying by a value expands the range
System.out.println();
System.out.println("Random doubles in [0,10):");
for (int i=0; i<5; i++)
{
double value = Math.random() * 10;
System.out.println(value);
}
// Adding a value translates the range
System.out.println();
System.out.println("Random doubles in [200,210):");
for (int i=0; i<5; i++)
{
double value = Math.random() * 10 + 200;
System.out.println(value);
}
// Casting to int gives the integer portion of the floating
// point number (drops everything past the decimal point).
System.out.println();
System.out.println("Random integers in [0,100):");
for (int i=0; i<5; i++)
{
int value = (int)(Math.random() * 100);
System.out.println(value);
}
}
}
Output:
Random doubles in [0,1):
0.6072477121950746
0.4468707050134336
0.8174659472411745
0.8554302954625477
0.7670180677386557
Random doubles in [0,10):
8.882325708884004
3.916573396706827
1.7936515121928154
0.09970099696123724
7.949602133962173
Random doubles in [200,210):
203.87487169213756
204.08627017080548
206.92141091798877
205.07069594897487
202.36813722834594
Random integers in [0,100):
28
43
78
97
66