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
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
}
}
标签:java,String,永不,订单号,SimpleDateFormat,Java,fourRandom,size
来源: https://www.cnblogs.com/sinosoft/p/14373070.html