2021SC@SDUSC
流水号生成
在本项目中,流水号生成的规则如下:
流水号的基本形式为一位字母+两位数字 如A01
随着流水号的增加,数字在不断变化00 ->99,字母也在增加 A->Z
getNextYouBianCode()
private static final int numLength = 2;
public static final int zhanweiLength = 1+numLength;
numLength
为数字位数,zhanweiLength
为总位数
getNextYouBianCode()
方法的功能为根据前一个code,获取同级下一个code
由于代码比较长,先分步进行表述:
if (code == null || code =="") {
String zimu = "A";
String num = getStrNum(1);
newcode = zimu + num;
如果code为空时,则按照“一位字母+两位数字”的形式构建流水号,第一个字符自然是A01
else {
String before_code = code.substring(0, code.length() - 1- numLength);
String after_code = code.substring(code.length() - 1 - numLength,code.length());
char after_code_zimu = after_code.substring(0, 1).charAt(0);
Integer after_code_num = Integer.parseInt(after_code.substring(1));
String nextNum = "";
char nextZimu = 'A';
在code不为空时,则要程序是流水号依次递增。有三个地方需要着重考虑:
1.先判断数字等于99时,则计数从01重新开始,递增
if (after_code_num == getMaxNumByLength(numLength)) {
nextNum = getNextStrNum(0);
} else {
nextNum = getNextStrNum(after_code_num);
}
2.判断数字等于99*,则字母从A重新开始,递增
if(after_code_num == getMaxNumByLength(numLength)) {
nextZimu = getNextZiMu(after_code_zimu);
}else{
nextZimu = after_code_zimu;
}
3.在字母和数字均达到最高位时,即数字为为99,字母位为Z时,需要将流水号的位数进行扩展,即Z99的下一个code为Z99A01
if ('Z' == after_code_zimu && getMaxNumByLength(numLength) == after_code_num) {
newcode = code + (nextZimu + nextNum);
} else {
newcode = before_code + (nextZimu + nextNum);
}
}
这样,流水号就可以依次有序增加了
getSubYouBianCode()
getSubYouBianCode()
函数的作用是根据父亲code,获取下级的下一个code
举例:父亲CODE:A01,当前CODE:A01B03,获取的code:A01B04
public static synchronized String getSubYouBianCode(String parentCode,String localCode) {
if(localCode!=null && localCode!=""){
return getNextYouBianCode(localCode);
}else{
parentCode = parentCode + "A"+ getNextStrNum(0);
}
return parentCode;
}
其中,parentCode是上级code,localCode是同级code
private static String getNextStrNum(int num) {
return getStrNum(getNextNum(num));
}
private static String getStrNum(int num) {
String s = String.format("%0" + numLength + "d", num);
return s;
}
将数字前面位数补零,在数字仅有一位时,如1需要将其补充为01
private static int getNextNum(int num) {
num++;
return num;
}
获取下一个数字
private static char getNextZiMu(char zimu) {
if (zimu == 'Z') {
return 'A';
}
zimu++;
return zimu;
}
获取下一个字母
private static int getMaxNumByLength(int length){
if(length==0){
return 0;
}
String max_num = "";
for (int i=0;i<length;i++){
max_num = max_num + "9";
}
return Integer.parseInt(max_num);
}
通过这个方法可以获取与所需流水号相同长度的最大流水号,如A01的最大流水号时A99。
注意max_num一开始时空字符串,通过加法与“9”相连接,最后别忘了将max_num从字符串转化成数据。