0Pricing
Java Academy · Lesson

Random Ranges and Shuffling

Bounded randoms and collections shuffle.

Ranges and Shuffling

Real programs rarely want 0 to bound-1. This lesson covers arbitrary ranges, randomly shuffling collections, and picking random elements.

A Custom Range Formula

To produce an int from min to max inclusive, use min + rng.nextInt(max - min + 1).

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random rng = new Random();
        int min = 10, max = 20;
        int value = min + rng.nextInt(max - min + 1);
        System.out.println("10 to 20: " + value);
    }
}

All lessons in this course

  1. The Math Class
  2. Generating Random Numbers
  3. Random Ranges and Shuffling
  4. Math Rounding and Limits
← Back to Java Academy