1. 程式人生 > >產生隨機數工具類

產生隨機數工具類

import ack long com string pre nbsp tex ati

package com.qiyuan.util;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;

public class RandomNumberUtil {
    
    private static final int[] prefix = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };  
      
    /** 
     * 隨機產生最大為18位的long型數據(long型數據的最大值是9223372036854775807,共有19位) 
     * 
@param digit:用戶指定隨機數據的位數 */ public static long randomLong(int digit) { if (digit >= 19 || digit <= 0) throw new IllegalArgumentException("digit should between 1 and 18(1<=digit<=18)"); String s = RandomStringUtils.randomNumeric(digit - 1);
return Long.parseLong(getPrefix() + s); } /** * 隨機產生在指定位數之間的long型數據,位數包括兩邊的值,minDigit<=maxDigit * @param minDigit:用戶指定隨機數據的最小位數 minDigit>=1 * @param maxDigit:用戶指定隨機數據的最大位數 maxDigit<=18 */ public static long randomLong(int minDigit, int maxDigit) {
if (minDigit > maxDigit) { throw new IllegalArgumentException("minDigit > maxDigit"); } if (minDigit <= 0 || maxDigit >= 19) { throw new IllegalArgumentException("minDigit <=0 || maxDigit>=19"); } return randomLong(minDigit + getDigit(maxDigit - minDigit)); } private static int getDigit(int max) { return RandomUtils.nextInt(max + 1); } /** * 保證第一位不是零 * * @return */ private static String getPrefix() { return prefix[RandomUtils.nextInt(9)] + ""; } public static void main(String[] args) { System.out.println("隨機產生最大為18位的long型數據,用戶指定位數================"+RandomNumberUtil.randomLong(10)); System.out.println(" 隨機產生在指定位數之間的long型數據,位數包括兩邊的值================"+RandomNumberUtil.randomLong(1,18)); } }

產生隨機數工具類