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.5162699929153137
0.18318407415979443
0.12830840241404018
0.32471275605012173
0.5054007140208051
Random doubles in [0,10):
7.460032744877104
1.2052875411524455
4.315933425387057
1.2129170344158258
6.786165899063899
Random doubles in [200,210):
206.8766194590549
207.40846740364194
209.9356133241234
207.4769467064515
207.61992616079704
Random integers in [0,100):
4
27
91
52
50