• 产生随机数工具类


    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));
        }
    }
  • 相关阅读:
    MySQL修改时区的方法小结
    MYSQL日期 字符串 时间戳互转
    2017php经典面试题
    PHP获得真实客户端的真实IP REMOTE_ADDR,HTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR
    开放api接口签名验证
    MySql之ALTER命令用法详细解读(转)
    easyUI datagrid 清空
    webApi文档好帮手-apidoc使用教程
    驼峰命名和下划线命名互转php实现
    SQL Server 数据导入Mysql详细教程
  • 原文地址:https://www.cnblogs.com/javahr/p/8321387.html
Copyright © 2020-2023  润新知