Random Number Cheat Sheet
by , 10-27-2012 at 04:00 AM (1022 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:
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:import java.util.Random;
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.Java Code:private static Random generator;
After that you will have to initialize your new generator:
This can be done at the same time as when 'generator' is created, like:Java Code:generator = new Random();
To generate one random integer:Java Code:private static Random generator = new Random();
To generate one random integer from 0 up to, but NOT including MAX:Java Code:int nextInt; nextInt = generator.nextInt();
To generate one random integer between 1 through MAX:Java Code:final int MAX = 24; int nextInt; nextInt = generator.nextInt(MAX);
To generate one real number from 0 up to, but NOT including 1: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 MAX:Java Code:double nextDouble; nextDouble = generator.nextDouble();
Java Code:final double MAX = 100; double nextDouble; nextDouble = generator.nextDouble() * MAX;









Email Blog Entry
License4J 4.0
Yesterday, 12:23 AM in Java Software