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
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM