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.13765537844612574
0.4091819668078627
0.10506822087873102
0.18567324231015014
0.23575796680321326
Random doubles in [0,10):
5.812356097424543
6.390531526572508
7.345451967145165
6.834542244964801
7.81518211371223
Random doubles in [200,210):
207.4794637544778
201.2552832493439
206.07043932941605
204.45819642572525
207.01052211188593
Random integers in [0,100):
15
89
96
96
3