comp102 lec 5.0
TRANSCRIPT
Random Numbers
•http://www.cs.geneseo.edu/~baldwin/reference/random.html
Two Methods
By using Random Library ClassBy using Math Library Class
RANDOM CLASS
Random Class
To use a classImport the class library
import java.util.Random;OR
import java.util.*;
Create an object of classRandom “name of object” = new Random()E.g
•Random rand = new Random();
Generate a Random Number Integer
Have/Declare an integer variableint a;
Assign it a random valuea=“object”.nextInt(“Value to define Range”);E.g
a = rand.nextInt(100);If value is 100, range is 0 – 99Value will define the range as starting from 0 to one less than the value
Define Ranges, where A is an Integer and rand is Random Object
A = rand.nextInt(100)A = rand.nextInt(10)A = rand.nextInt(101)A = rand.nextInt(99)A = rand.nextInt(100) + 5A = rand.nextInt(100) – 10A = rand.nextInt(10) + 1A = rand.nextInt(101)+5A = rand.nextInt(10) -10
0 - 990 - 90 - 1000 - 980 – 99 and then add 5 to it => 5-1040 -99 and then subtract 10 => -10 – 890 – 9 and then add 1 => 1 - 100-100 and then add 5 => 5 - 1050-9 and then subtract 10 => -10 – (-1)
What if I have to generate a Random Number from 0 – 50,
both inclusiveA = rand.nextInt(50);A = rand.nextInt(51);A = rand.nextInt(100)-50;A = rand.nextInt(50)+1;
Will generate a random number
from 0 -49Will generate a random
number from 0 - 50
Will generate a Random Number from 0 – 99 first
and then subtract 50 from generated number
thus defines the range as[0 – 50] – [99 – 50] =
-50 - 49
Will generate a random number from 0 – 49 and then will add 1 to it, makes
range as 1 – 50
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;
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();
CLASS MATH
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]
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]