天天看點

java 字母自增_JAVA 字母數字混合自增(4位)

public static int getAscNum(String st) {

byte[] gc = st.getBytes();

int ascNum = (int) gc[0];

return ascNum;

}

public static String getNumAsc(int num) {

char a = (char)num;

return a+"";

}

//主方法

private String getNextCashNumber(String number) {

if (StringUtil.isEmpty(number)) {

return "A001";

}

String pre = number.replaceAll("[^a-zA-Z]", "");// 擷取字母部分

String counterStr = number.replaceAll("[^0-9]", "");

// 字元+數字

if (!StringUtil.isEmpty(counterStr)) {

int counter = Integer.parseInt(counterStr);// 擷取數字部分

counter++;

DataMap checkMap = CheckNumGreaterMax(pre, counter);

if (!(boolean) checkMap.get("success")) {

counterStr = checkMap.get("counterStr").toString();

return pre + counterStr;

}

// A999->AB01

pre = letterCounter(pre);

if (pre.length() > 4) {

return "";

}

if (pre.length() < 4) {

pre += String.format("%0" + (4 - pre.length()) + "d", 1);

}

return pre;

}

String str = letterCounter(pre);

return str;

}

private String letterCounter(String str) {

int len = str.length();

int startI = len - 1;

String tempA = "";

String tempB = "";

while (true) {

tempA = "";

if (startI > 0) {

tempA = str.substring(0, startI);

}

if (startI < 0 && len == 0) {

tempA = str;

tempB = "A";

break;

} else {

tempB = str.substring(startI, len);

int lastCode = StringUtil.getAscNum(tempB);

lastCode++;

if (lastCode <= 90) {

tempB = StringUtil.getNumAsc(lastCode);

break;

}

startI--;

len--;

}

}

String newStr = tempA + tempB;

while (newStr.length() < str.length()) {

newStr += "A";

}

return newStr;

}

//檢查數字計數器是否超額

private DataMap CheckNumGreaterMax(String pre, int counter) {

int preL = pre.length();

int maxConter = 0;

String str = "";

switch (preL) {

case 1:

maxConter = 999;

str = String.format("%03d", counter);

break;

case 2:

maxConter = 99;

str = String.format("%02d", counter);

break;

case 3:

maxConter = 9;

str = String.format("%01d", counter);

break;

}

DataMap map = new DataMap();

if (counter > maxConter) {

map.put("success", true);

} else {

map.put("success", false);

map.put("counterStr", str);

}

return map;

}