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.7030019960782311
0.8521907192554905
0.9948945901901922
0.44811104000326696
0.27362712316854454
Random doubles in [0,10):
2.7803173327709905
3.095263702858727
4.320104692884401
3.0109274233228045
2.6252540083362796
Random doubles in [200,210):
203.39452079196377
200.5272512460542
202.45318694782225
203.95837584976454
203.63935171111916
Random integers in [0,100):
5
23
59
13
28