random_examples - matthew9510/Studies GitHub Wiki

The Random Object

Basics

import java.util.Random; makes Java's Random class available to the program.

Random rand = new Random(); creates a new random number generator object named rand. The method call rand.nextInt(X) can then be used to get a random number ranging from 0 to X - 1.

Uses of the new Object named rand:

rand.nextInt(), with no number between the (), returns a random value that could be any integer (of int type), positive or negative.

rand.nextInt(10) produces a random number between 0 and 9.

rand.nextInt(maxNum - minNum + 1) + minNum The code adds 1 to obtain a random value between minNum and maxNum.

rand.nextInt( 9 - 0 + 1) + 1 The code adds 1 to obtain values between 1 and 9.

Making a pseudo-random number generator

A pseudo-random number generator produces a specific sequence of numbers based on a seed number, that sequence seeming random but always being the same for a given seed.

  • Random() seeds the pseudo-random number generator with a number based on the current time. That number is essentially random, so the program will get a different pseudo-random number sequence on each run.

  • Random(num) will seed the generator with the value num, where num is any integer (actually, any "long" value).

An important part of testing or debugging a program is being able to have the program run exactly the same across multiple runs, most programming languages use a pseudo-random number generation approach to solve this problem.

A pseudo-random number generator produces a specific sequence of numbers based on a seed number, AKA a channel to receive a specific sequence. A sequence that might seeming random but always being the same for a given seed.

Look at RandomExamples.java to follow along