Java Random Int randInt(int min, int max)

Here you can find the source of randInt(int min, int max)

Description

Greg Case: Returns a pseudo-random number between min and max, inclusive.

License

Open Source License

Parameter

Parameter Description
min Minimum value
max Maximum value. Must be greater than min.

Return

Integer between min and max, inclusive.

Declaration

public static int randInt(int min, int max) 

Method Source Code


//package com.java2s;
import java.util.Random;

public class Main {
    /**/*from   ww w  .  ja  va  2s .c o  m*/
     * @param min Minimum value
     * @param max Maximum value. Must be greater than min.
     * @param exception Number between min & max that must be excluded from 
     * speudo random return value possibilities.
     * 
     * @return Integer between min and max, inclusive.
     * @see java.util.Random#nextInt(int)
     */
    public static int randInt(final int min, final int max, final int exception) {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        final Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = -1;

        do {
            randomNum = rand.nextInt((max - min) + 1) + min;
        } while (randomNum == exception);

        return randomNum;
    }

    /**
     * Greg Case:
     * Returns a pseudo-random number between min and max, inclusive. The
     * difference between min and max can be at most
     * <code>Integer.MAX_VALUE - 1</code>.
     *
     * @param min Minimum value
     * @param max Maximum value. Must be greater than min.
     * @return Integer between min and max, inclusive.
     * @see java.util.Random#nextInt(int)
     */
    public static int randInt(int min, int max) {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        final Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }
}

Related

  1. randInt()
  2. randInt(int l)
  3. randInt(int low, int high)
  4. randInt(int max)
  5. randint(int max)
  6. randInt(int min, int max)
  7. randInt(int min, int max)
  8. randInt(int min, int max)
  9. randInt(int min, int max)