HIDE NAV

Random Class

The below command line program demonstrates some of the pseudo-random number generation methods availale in the Random class.
The methods in Random are mostly instance methods, so an object instance of Random must first be created. In the below example the object is named randGen, but may have any valid variable name
For more information visit the Core Java API page for the class java.util.Random.

Main.java


package ceccs;

import java.util.Random;

public class Main {

    public static void main(String[] args) {
        int i = 0;

        /** generate 20 random number with Math.random()*/
        while (i < 20) {
            double randNum = Math.random();
            System.out.println(randNum);
            i++;
        }

        /** generate 20 random number with Random.nextInt()*/
        System.out.println("-------------------------------");
        i = 0;
        Random randGen = new Random();
        while (i < 20) {
            int randInt = randGen.nextInt();
            System.out.println(randInt);
            i++;
        }

        /** generate 20 random number with Random.nextInt(int bound)*/
        System.out.println("-------------------------------");
        i = 0;
        /** generate 20 random number with Math.random()*/
        while (i < 20) {
            int randInt = randGen.nextInt(3);
            System.out.println(randInt);
            i++;
        }

        /** generate 20 random true/false values with Random.nextBoolean()*/
        System.out.println("-------------------------------");
        boolean randBool;
        /** generate 20 random number with Math.random()*/
        i = 0;
        while (i < 20) {
            randBool = randGen.nextBoolean();
            System.out.println(randBool);
            i++;
        }

    }
}