Java怎么生成一个指定长度的字符串?
展开全部
public class GenString {
public static String gen(int length) {
char[] ss = new char[length];
int[] flag = {0,0,0}; //A-Z, a-z, 0-9
int i=0;
while(flag[0]==0 || flag[1]==0 || flag[2]==0 || i<length) {
i = i%length;
int f = (int) (Math.random()*3%3);
if(f==0)
ss[i] = (char) ('A'+Math.random()*26);
else if(f==1)
ss[i] = (char) ('a'+Math.random()*26);
else
ss[i] = (char) ('0'+Math.random()*10);
flag[f]=1;
i++;
}
return new String(ss);
}
}
public static String gen(int length) {
char[] ss = new char[length];
int[] flag = {0,0,0}; //A-Z, a-z, 0-9
int i=0;
while(flag[0]==0 || flag[1]==0 || flag[2]==0 || i<length) {
i = i%length;
int f = (int) (Math.random()*3%3);
if(f==0)
ss[i] = (char) ('A'+Math.random()*26);
else if(f==1)
ss[i] = (char) ('a'+Math.random()*26);
else
ss[i] = (char) ('0'+Math.random()*10);
flag[f]=1;
i++;
}
return new String(ss);
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询