Returns a random integer between 0 (Zero) inclusive and MAX inclusive. - Android java.util

Android examples for java.util:Random Integer

Description

Returns a random integer between 0 (Zero) inclusive and MAX inclusive.

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    /**//from   w ww.  jav a 2  s.  co  m
     * Returns a random integer between 0 (Zero) inclusive and MAX inclusive.
     * <br>
     * If negative value is specified, then range is between [n, 0].
     * <br>
     * Internally calls {@link #getRandomIntegerWithinRange(int, int)}.
     * <br>
     *  E.g., 
     * 
     * @param max - value inclusive
     * @return an int between 0 inclusive and MAX inclusive.
     */
    public static int getRandomInteger(int max) {
        int min = 0;
        if (max < 0) {
            int temp = max;
            max = 0;
            min = temp;
        }
        return getRandomIntegerWithinRange(min, max);
    }

    /**
     * Returns a random number between MIN inclusive and MAX inclusive.
     * <br>
     * E.g., 
     * @param min
     *            value inclusive
     * @param max
     *            value inclusive
     * @return an int between MIN inclusive and MAX exclusive.
     */
    public static int getRandomIntegerWithinRange(int min, int max) {
        if (min == max) {
            return max;
        }
        if (max < min) {
            int temp = max;
            max = min;
            min = temp;
        }
        Random r = new Random();
        return r.nextInt(max - min + 1) + min;
    }
}

Related Tutorials