我的规则是第一位作为头,后面所为流水号,当然头也是可变的,从1到Z,只是在流水号从XXX001用到XXX999,z最后用到XXXZZZ的时候,头才会加一个,先贴代码:
public static void main(String[] args) throws Exception {
String customDotNum = customDotNum(“10ZZZ”, 4);
System.out.println(customDotNum);
}
/**
-
生成当前头+流水序号
-
@param nowNetwork 当前头+流水序号
-
@param serialLength 流水序号长度
-
@return 返回下一个头+流水序号
-
@throws Exception
*/
private static String customDotNum(String nowNetwork, int serialLength) throws Exception {
// 如果是什么都没有
StringBuilder stringBuilder = new StringBuilder();
if (nowNetwork == null || nowNetwork.length() == 0 || “null”.equals(nowNetwork)) {
stringBuilder.append(“A”);
for (int i = 0; i < serialLength; i++) {
stringBuilder.append(“0”);
}
} else {
stringBuilder.append(nowNetwork);
}if (stringBuilder.length() != serialLength + 1) {
throw new Exception(“参数长度与传入长度不符:network:” + stringBuilder.toString() + " serialLength:" + serialLength);
}
if (serialLength < 1 || serialLength > 12) {
throw new Exception(“长度格式有误,长度必需在1-12之间”);
}String header = stringBuilder.substring(0, 1);
String driver = “”;
try {
driver = driver(stringBuilder.substring(1));
} catch (Exception e) {
char charAt = stringBuilder.charAt(0);
if (charAt == ‘Z’) {
throw new Exception(“数据头已溢出”);
}
if (charAt == ‘9’) {
charAt = ‘@’;
}
AtomicInteger atomic = new AtomicInteger(charAt);
header = String.valueOf((char) atomic.incrementAndGet());
StringBuilder stringBuilder1 = new StringBuilder();
for (int i = 0; i < serialLength; i++) {
stringBuilder1.append(“0”);
}
try {
driver = driver(stringBuilder1.toString());
} catch (Exception e0) {
e0.printStackTrace();
}
}
return header + driver;
}
/**
-
生成流水序号
-
@param driver 当前头+流水序号
-
@return 返回下一个流水序号
-
@throws Exception
*/
public static String driver(String driver) throws Exception {
driver = driver.toUpperCase();
char[] charArray = driver.toCharArray();
AtomicInteger z = new AtomicInteger(0);
for (int i = charArray.length - 1; i >= 0; i–) {
char c = charArray[i];
// 先判断满Z进1的情况
if (c == ‘Z’) {
if (i == 0) {
throw new Exception(“数据已溢出”);
}
charArray[i] = ‘A’;
z.set(1);
continue;
}if (c == ‘9’) {
// 如果到了第一位还是9
if (i == 0) {
charArray[i] = ‘A’;
break;
}
charArray[i] = ‘0’;
z.set(1);
continue;
}
// 如果等于1则需要进位1
if (z.intValue() == 1 || i == charArray.length - 1) {
AtomicInteger atomic = new AtomicInteger©;
charArray[i] = (char) atomic.incrementAndGet();
z.set(0);
break;
}
}return String.valueOf(charArray);
}