62,614
社区成员
发帖
与我相关
我的任务
分享
public class Tools {
//计数最大长度,默认为0,表示无限大。
public static int maxLength = 0;
/**
* 以 0-9 A-Z a-z 范围的字符计数器函数。计数顺序是以上述字符的ascii码的大小来排序。
* 考虑到可能运行在多线程环境,加了同步锁。
* @param param 计数参数
* @return param加1后的数值
* @throws Exception
*/
public static synchronized String getNextValue(String param) throws Exception{
//空值校验
if(param == null || param.length() == 0){
return "0";
}
//长度校验
if(param.length() == 0 || param.length() > 6){
throw new Exception("参数不合法,长度要大于0且小于等于6位!");
}
//非法字符校验
char[] paramChars = param.toCharArray();
for(int i=0;i<paramChars.length;i++){
char chr = paramChars[i];
boolean flag = (chr >= 48 && chr <= 57) || (chr >= 65 && chr <= 90) || (chr >= 97 && chr <= 122);
if(!flag){
throw new Exception("参数不合法,含有非 0-9 A-Z a-z 的字符!");
}
}
//计数上限校验,不能超过最大长度位数。
if(maxLength > 0){
StringBuilder sb = new StringBuilder();
for(int i=0;i<maxLength;i++){
sb.append('z');
}
if(sb.toString().equals(param)){
throw new Exception("参数不合法,已达上限'" + sb.toString() + "'!");
}
}
boolean carry = false;
for(int i = paramChars.length-1;i>=0;i--){
char chr = paramChars[i];
//逢'z'进位
if(chr == 'z'){
paramChars[i] = '0';
if(i == 0){
carry = true;
}
}else{
if(chr == '9'){
chr = 'A';
}else if(chr == 'Z'){
chr = 'a';
}else{
chr++;
}
paramChars[i] = chr;
carry = false;
break;
}
}
param = new String(paramChars);
if(carry){
param = "1" + param;
}
return param;
}
public static void main(String[] args) {
Tools.maxLength = 6;
String value = "";//表示从0开始计数。
long count = 0;
try {
while(true){
value = Tools.getNextValue(value);
count++;
System.out.println(value);
//控制输出的最大数值。
if("zzz".equals(value)){
break;
}
}
System.out.println("计数次数:" + count);
} catch (Exception e) {
e.printStackTrace();
}
}
}