Comp102 lec 5.0

319 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
319
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Comp102 lec 5.0

  1. 1. Random Numbers•http://www.cs.geneseo.edu/~baldwin/reference/random.html
  2. 2. Two MethodsBy using Random Library ClassBy using Math Library Class
  3. 3. RANDOM CLASS
  4. 4. Random ClassTo 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. 5. Generate a Random Number IntegerHave/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. 6. Define Ranges, where A is an Integer and rand is Random ObjectA= rand.nextInt(100) 0 - 99A= rand.nextInt(10) 0-9A= rand.nextInt(101) 0 - 100A= rand.nextInt(99) 0 - 98A= rand.nextInt(100) + 0 – 99 and then add 5 to it =>5 5-104A= rand.nextInt(100) – 0 -99 and then subtract 10 =>10 -10 – 89A= rand.nextInt(10) + 1 0 – 9 and then add 1 => 1 - 10 0-100 and then add 5 => 5 - 105A= rand.nextInt(101)+5 0-9 and then subtract 10 => -10 – (-A= rand.nextInt(10) -10 1)
  7. 7. What if I have to generate aRandom 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. 8. What if I have to generate aRandom 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. 9. Random Real NumbersTo generate a random real numberuniformly distributed between 0and 1, use the "nextDouble"message. This message takes noparameters. For example...double r = rand.nextDouble();
  10. 10. CLASS MATH
  11. 11. Math.random() calldouble 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. 12. Generate Integer Random NumberMath.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]

×