View RSS Feed

penguinCoder

Random Number Cheat Sheet

Rate this Entry
by , 10-27-2012 at 04:00 AM (1753 Views)
Just for FYI, computers cannot generate actual random numbers. They are machines, and they do what they are told; and therefore cannot just choose a number at random. Mathematicians would call the process this process 'psuedo-random' number generation, but I didn't feel that made a good title so, whatever.. Just covering all the bases.

First you will have to import the library:
Java Code:
import java.util.Random;
Next, you create a random number generator; most of the time is it made a static data member so that it can be shared by all the methods:
Java Code:
private static Random generator;
The keyword 'generator' is just the variable name, and can be changed to whatever you see fit; but it is good practice to choose descriptive variable names.

After that you will have to initialize your new generator:
Java Code:
generator = new Random();
This can be done at the same time as when 'generator' is created, like:
Java Code:
private static Random generator = new Random();
To generate one random integer:
Java Code:
int nextInt;
nextInt = generator.nextInt();
To generate one random integer from 0 up to, but NOT including MAX:
Java Code:
final int MAX = 24;
int nextInt;
nextInt = generator.nextInt(MAX);
To generate one random integer between 1 through MAX:
Java Code:
final int MAX = 24;
int nextInt;
nextInt = generator.nextInt(MAX) +1;
To generate one real number from 0 up to, but NOT including 1:
Java Code:
double nextDouble;
nextDouble = generator.nextDouble();
To generate one real number from 0 up to, but NOT including MAX:
Java Code:
final double MAX = 100;
double nextDouble;
nextDouble = generator.nextDouble() * MAX;

Submit "Random Number Cheat Sheet" to Facebook Submit "Random Number Cheat Sheet" to Digg Submit "Random Number Cheat Sheet" to del.icio.us Submit "Random Number Cheat Sheet" to StumbleUpon Submit "Random Number Cheat Sheet" to Google

Comments