JAVA:主键解决方法,1:最大值+1

/**

* 判断字符串是不是数字

*

* @param str

* @return true OR false

* @see isNumeric("abc") = false

* @see isNumeric("123") = true

*/

public static boolean isNumeric(String str) {

Pattern pattern = Pattern.compile("[0-9]*");

Matcher isNum = pattern.matcher(str);

if (!isNum.matches()) {

return false;

}

return true;

}

/**

* 得到01,或者001

*

* @param segNum

* 段长度

* @return String

* @see getNewMaxStr(2) = "01"

* @see getNewMaxStr(3) = "001"

* @see getNewMaxStr(4) = "0001"

*/

public static String getNewMaxStr(int segNum) {

String result = "";

result = fillStr("0", segNum - 1) + 1;

return result;

}

/**

* 通过字符串得到 字符串+1的最大数

*

* @param str

* 字符串

* @param segNum

* 段长度

* @return String

* @see getNewMaxStr("002145", 3)=002146;

* @see getNewMaxStr("002005", 3)=002006;

* @see getNewMaxStr("002999", 2)="error: '[0029][99]' segNum is end the

* MAXSegNum."

* @see getNewMaxStr("4123563364", 5)=4123563365;

*/

public static String getNewMaxStr(String str, int segNum) {

String result = "";

if (isNumeric(str) == false) {

// 判断是否数字

result = "error: '" + str + "' not a Number.";

} else {

// 字符串长度是否能整除 段长

int strLength = str.length();

int mod = strLength % segNum;

if (mod != 0) {

result = "error: '" + str + "' not Mod segNum.";

} else {

String endSegStr = str.substring(strLength - segNum, strLength);

String stratSegStr = str.substring(0, strLength - segNum);

// System.out.println("endSegStr:" + endSegStr);

// System.out.println("stratSegStr:" + stratSegStr);

// 设置后位段数最大值

// 将后位段字符str转成int,并 +1, 并取字符串,判断是否已经到最大值

int segNumMaxStrInt = Integer.parseInt(endSegStr) + 1;

String segNumMaxStr = String.valueOf(segNumMaxStrInt);

if (segNumMaxStr.length() == (segNum + 1)) {

result = "error: '[" + stratSegStr + "][" + endSegStr

+ "]' segNum is end the MAXSegNum.";

} else {

// 最大数 + 1; 如:100, 1000, 10000等

int segNumMax = Integer

.parseInt("1" + fillStr("0", segNum));

// System.out.println("segNumMax:" +

// String.valueOf(segNumMax + segNumMaxStrInt));

String segNumStr = String.valueOf(

segNumMax + segNumMaxStrInt).substring(1,

segNum + 1);

result = stratSegStr + segNumStr;

}

}

}

return result;

}

}