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.896588718561671
0.7408657216479771
0.739947631046642
0.996346411215559
0.7939380129120205
Random doubles in [0,10):
9.748394697747957
3.2287700943489286
9.586377778766629
2.6638307484032886
4.52409417104413
Random doubles in [200,210):
207.84140999410278
203.4716756684343
205.85348166585598
206.03430773929838
209.94130378701072
Random integers in [0,100):
13
44
3
75
83