Pseudorandom values via a java.util.Random object

Use a java.util.Random object to generate pseudorandom values while your program is running.  The Random object can be imagined as black box with a few buttons that when pressed spit out pseudorandom numbers with various properties depending upon which button was pressed (method was called). 

The Random object can be created with a seed.  In which case the stream of values will be generated in a repeatable order.

input stream contains "123 abc 12\nJava is fun!\n

0. import the java.util.Random class (so that you do not need to write java.util.Random)

import java.util.Scanner ;
public class MyRandomClassName {
   ...

1. Declare a reference variable for the Random object

Random rng ;

2. Create a Random object and assign it to the Scanner variable you created.

int seed = 17;  // or any seed value we want
rng = new Random( seed );

3. Get a random integer in the full range of integer values.

int aRandValue = rng.nextInt();
System.out.print( "aRandValue = " + aRandValue );

4. Get a random integer in the range of [0,n). (includes 0, but not n)

int n = 10;
int anotherRandValue = rng.nextInt(n);
System.out.print( "anotherRandValue = " + aRandValue ); // 0-9, inclusive

5. Get a random double value in the range of [0,1). (includes 0, but not 1)

double aDoubleRandValue = rng.nextDouble();
System.out.print( "aDoubleRandValue = " + aDoubleRandValue );

6. Get a random integer in the range of [m,n], inclusive of both m and n.

Left for students to figure out on their own.

© 2014 Debra Deppeler, All rights reserved.