Random Numbers Using The Random Class December 23
Random Numbers Using The Random Class December 23, 2021 The Random Class and its Methods 1
Random Numbers in Applications • Some applications such as games and simulations require the use of randomly generated numbers – Tossing a coin: an even number may represent a head an odd number may represent a tail – A random number between one and six may represent the roll of one die – A random number between 1 and 52 may represent a particular card in a deck of cards – A roulette wheel has 38 slots numbered 0 -36 and 00. 00 One may use a random number between 0 and 37 to simulate a spin of the wheel. December 23, 2021 The Random Class and its Methods 2
The Random Class • The Java API has a class named Random for this purpose. • To use the Random class, use the following import statement and create an instance of the class. import java. util. Random; Random random. Number = new Random(); December 23, 2021 The Random Class and its Methods 3
Some Methods of the Random Class Method Description next. Double() Returns the next random number as a double. The number will be within the range of 0. 0 and 1. 0. next. Float() Returns the next random number as a float. The number will be within the range of 0. 0 and 1. 0. next. Int() Returns the next random number as an int. The number will be within the range of an int, which is – 2, 147, 483, 648 to +2, 147, 483, 647. This is Integer. MIN_VALUE to Integer. MAX_VALUE. next. Int(int n) This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 to n.
Using the Random Class • The methods in the previous table generate uniformly distributed random numbers – Each value in the range is equally likely to occur – The type of data returned is determined by the name of the method (see previous slide – next. Double, next. Int, …) December 23, 2021 The Random Class and its Methods 5
Range of Random Numbers • The next. Int (n) method generates a random number in the range between 0 and n. n – 0 is included in the range but n is not included in the range – next. Int (4) would generate 0, 0 1, 2, or 3 with equal probability. No other result is possible. – To generate a random integer between min and max inclusively, use an expression such as the following where r is an object of Random: Random int num = r. next. Int (max – min + 1) + min; // random int between 11 and 15 inclusively int ans = r. next. Int (5) + 11; December 23, 2021 The Random Class and its Methods 6
Range of Doubles • To generate a double between d 1 and d 2 use: double rand = r. next. Double ( ) * (d 2 – d 1) + d 1; • To generate a random double between 800 and 1000 we would use double value = r. next. Double( ) * (200. ) + 800. ; December 23, 2021 The Random Class and its Methods 7
Sample output Random int’s between 0 and 99 December 23, 2021 The Random Class and its Methods 8
- Slides: 8