4. Random Class
To use a class
Import the class library
import java.util.Random;
OR
import java.util.*;
Create an object of class
Random “name of object” = new Random()
E.g
• Random rand = new Random();
5. Generate a Random Number
Integer
Have/Declare an integer variable
int a;
Assign it a random value
a=“object”.nextInt(“Value to define
Range”);
E.g
a = rand.nextInt(100);
If value is 100, range is 0 – 99
Value will define the range as starting
from 0 to one less than the value
6. Define Ranges, where A is an Integer
and rand is Random Object
A= rand.nextInt(100) 0 - 99
A= rand.nextInt(10) 0-9
A= rand.nextInt(101) 0 - 100
A= rand.nextInt(99) 0 - 98
A= rand.nextInt(100) + 0 – 99 and then add 5 to it =>
5 5-104
A= rand.nextInt(100) – 0 -99 and then subtract 10 =>
10 -10 – 89
A= rand.nextInt(10) + 1 0 – 9 and then add 1 => 1 - 10
0-100 and then add 5 => 5 - 105
A= rand.nextInt(101)+5
0-9 and then subtract 10 => -10 – (-
A= rand.nextInt(10) -10 1)
7. What if I have to generate a
Random Number from 0 –Random
Will generate a
50,
Will generate a
both inclusivethen0subtractfrom
Number from 0 – 99 first
random number
and -49 50
fromWill generate random
Will generate number
generated a a
A = rand.nextInt(50); thus numberthe range50
defines from 0 - as
random number from
[0 – 49 and then will
0 – 50] – [99 – 50] =
A = rand.nextInt(51); -50 - 49
add 1 to it, makes
range as 1 – 50
A = rand.nextInt(100)-50;
A = rand.nextInt(50)+1;
8. What if I have to generate a
Random Number from 5 – 15
both inclusive?
a = rand.nextInt(15);
a = rand.nextInt(16);
a = rand.nextInt(10)+5;
a = rand.nextInt(11)+5;
9. Random Real Numbers
To generate a random real number
uniformly distributed between 0
and 1, use the "nextDouble"
message. This message takes no
parameters. For example...
double r = rand.nextDouble();
11. Math.random() call
double x = Math.random();
Returns a double value with a positive
sign, greater than or equal to 0.0 and
less than 1.0.
Will assign a value to x from [0.0 –
0.999]
12. Generate Integer Random
Number
Math.random()*10
[0.0 – 9.99]
Convert it into Integer by type casting
(int)(Math.random()*10)
[0 – 9]
Math.random()*100
[0.0 – 99.99]
Convert it into Integer by type casting
(int)(Math.random()*100
[0 – 99]