How do I generate a random array of numbers?

Using java.util.Random class we can create random data such as boolean, integer, floats, double. First you’ll need to create an instance of the Random class. This class has some next***() methods that can randomly create the data.

package org.kodejava.util;

import java.util.Arrays;
import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random r = new Random();

        // generate some random boolean values
        boolean[] booleans = new boolean[10];
        for (int i = 0; i < booleans.length; i++) {
            booleans[i] = r.nextBoolean();
        }
        System.out.println(Arrays.toString(booleans));

        // generate a uniformly distributed int random numbers
        int[] integers = new int[10];
        for (int i = 0; i < integers.length; i++) {
            integers[i] = r.nextInt();
        }
        System.out.println(Arrays.toString(integers));

        // generate a uniformly distributed float random numbers
        float[] floats = new float[10];
        for (int i = 0; i < floats.length; i++) {
            floats[i] = r.nextFloat();
        }
        System.out.println(Arrays.toString(floats));

        // generate a Gaussian normally distributed random numbers
        double[] doubles = new double[10];
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] = r.nextGaussian();
        }
        System.out.println(Arrays.toString(doubles));
    }
}

The result of the code snippet above are:

[true, true, false, true, false, true, true, false, false, true]
[34195704, 1462972230, -475641915, -1531017612, 332184915, 1555901473, -276309016, 1433394157, -451221924, -1178823255]
[0.3040716, 0.28814012, 0.34028566, 0.021003246, 0.49158317, 0.37954164, 0.5403056, 0.54187375, 0.7157934, 0.5964742]
[1.051268591002577, -1.1283332046139989, 0.8351395528722437, -0.24598168031182968, 0.7123515366756693, -0.9661681996105319, -1.6107009669125059, 0.43994917963255387, 1.1309345726165914, 1.2321618489324313]

For an example to create random number using the Math.random() method see How do I create random number?.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.