Generate a positive random integer - Android java.util

Android examples for java.util:Random Integer

Description

Generate a positive random integer

Demo Code


import java.util.Random;

public class Main{
    /** one copy of this class! */
    private static RandUtils m_rand = null;
    /** random number generator */
    private Random m_rng;
    /**//from w  w  w .jav  a2s.com
     * Generate a positive random integer
     * @return positive integer
     */
    public static int getPositiveInt() {
        int i = getObj().m_rng.nextInt();
        if (i < 0) {
            i = -i;
        }
        return i;
    }
    /**
     * Generate a positive random integer
     * @param limit numbers should be between 0 to limit-1
     * @return positive integer
     */
    public static int getPositiveInt(int limit) {
        int i = getObj().m_rng.nextInt();
        if (i < 0) {
            i = -i;
        }
        i %= limit;
        return i;
    }
    /**
     * Generate a positive random integer
     * @param limit numbers should be between 0 to limit-1
     * @param first the first number in the range first to first + limit - 1
     * @return positive integer
     */
    public static int getPositiveInt(int limit, int first) {
        int i = getObj().m_rng.nextInt();
        if (i < 0) {
            i = -i;
        }
        i %= limit;
        i += first;
        return i;
    }
    /**
     * Gets the object of this class
     * @return the desired object
     */
    public static RandUtils getObj() {
        if (m_rand != null) {
            return m_rand;
        }
        m_rand = new RandUtils();
        return m_rand;
    }
}

Related Tutorials