zoukankan      html  css  js  c++  java
  • Java 生成永不重复的订单号

    package com.taiping.test;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Random;
    
    public class Test12 {
        
        
        /**
         * 生成永不重复的订单号
         * @param startLetter  订单号开头字符串
         * @param size  订单号中随机的大写字母个数
         * @return
         */
        public static String createOrderNo(String startLetter,int size){
            
            String orderNo = null;
            
            Date nowDate = new Date();
            
            Random random = new Random();
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            
            //生成两位大写字母
            String keyArr = randomLetter(size);
        
            String fourRandom = random.nextInt(9999) + "";
            
            int randLength = fourRandom.length();
            
            //四位随机数,不足四位的补0
            if(fourRandom.length()<4){//不足四位的随机数补充0
                for(int i=1; i<=4-randLength; i++){
                    fourRandom = '0' + fourRandom;
                }
            }
            
            orderNo="NS"+keyArr+sdf.format(nowDate)+fourRandom;
            
            return orderNo;
        }
        
        /**
         * 生成大写字母
         * @param size
         * @return
         */
        public static String randomLetter(int size){
            String keyArr= "";
            char key = 0;
            boolean[] flag=new boolean[26];    //定义一个Boolean型数组,用来除去重复值
            for(int i=0;i<size;i++){     //通过循环为数组赋值
                Random rand=new Random();
                int index;
                do{
                    index=rand.nextInt(26);    //随机生成0-25的数字并赋值给index
                }while(flag[index]);    //判断flag值是否为true,如果为true则重新为index赋值
                key=(char) (index+65);        //大写字母的ASCII值为65-90,所以给index的值加上65,使其符合大写字母的ASCII值区间
                flag[index]=true;       //让对应的flag值为true
                
                keyArr +=key;
            }
            return keyArr;
        }
        
        /**
         * 测试
         * @param args
         */
        public static void main(String[] args) {
            
            System.out.println(createOrderNo("ND",2));
            
    //        NSBP202102041552086341
        }
    }
    作者:小鱼
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    linux 下vi中关于删除某段,某行,或者全部删除的命令
    Crontab的格式
    Crontab的格式
    Eclipse验证码
    jetty插件配置(开发)
    MongoDB使用手册
    Docker学习笔记(1) — docker 常用命令
    debian网易163更新服务器 源
    ssh安装过程
    HTML——列表标签
  • 原文地址:https://www.cnblogs.com/sinosoft/p/14373070.html
Copyright © 2011-2022 走看看