Java Random Number getRandomNumber(int digit)

Here you can find the source of getRandomNumber(int digit)

Description

Create a random integer number with digit number which was given by the caller.

License

BSD License

Parameter

Parameter Description
digit number of generated random number

Return

generated random number

Declaration

public static int getRandomNumber(int digit) 
    

Method Source Code

//package com.java2s;
/*L//from   www  .  j  a v  a 2 s  .  c om
 * Copyright SAIC, SAIC-Frederick.
 *
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/caadapter/LICENSE.txt for details.
 */

import java.util.*;

public class Main {
    /**
     * Create a random integer number with digit number which was given by the caller.
     *   For example, when digit number is 5, return value can be 34562 or 98123.
     * @param digit number of generated random number
     * @return generated random number
     */
    public static int getRandomNumber(int digit) // inserted by umkis 08/10/2006
    {
        if (digit <= 0)
            return 0;

        int in = 1;
        int la = 0;
        int sa = 0;
        for (int x = 0; x < digit; x++) {
            in = in * 10;
        }
        la = in;
        sa = la / 10;

        return getRandomNumber(sa, la);

    }

    /**
     * Create a random integer number between max and min number which was given by the caller.
     * @param min : number of generated minimum random number
     * @param max : number of generated maximum random number
     * @return generated random number
     */
    public static int getRandomNumber(int min, int max) // inserted by umkis 06/13/2007
    {
        if (min == max)
            return max;
        if (min > max) {
            int t = max;
            max = min;
            min = t;
        }
        Random rnd = new Random();
        int in = 0;
        int in1 = 0;
        if (max <= 0) {
            int min1 = 0 - max;
            int max1 = 0 - min;
            while (true) {
                in = rnd.nextInt();

                in1 = in % max1;
                if (in1 >= min1)
                    break;
            }
            in1 = 0 - in1;
        } else {
            while (true) {
                in = rnd.nextInt();

                in1 = in % max;
                if (in1 >= min)
                    break;
            }
        }
        return in1;
    }
}

Related

  1. getRandomNumber()
  2. getRandomNumber(final int from, final int to)
  3. getRandomNumber(final int maxInt, final int minInt)
  4. getRandomNumber(int bit)
  5. getRandomNumber(int bound)
  6. getRandomNumber(int len)
  7. getRandomNumber(int len)
  8. getRandomNumber(int length)
  9. getRandomNumber(int length)