您的位置 首页 java

初学Java,写了一个生成随机密码方法

 public class GeneratePasswd  {

// 随机字符串洗牌
public static String shuffle( char [] c) {
Random random = new Random();

for (int i = c.length -1; i > 0; i--) {
int p = random.nextInt(i+1);

char temp = c[i];
c[i]=c[p];
c[p]=temp;
}
return String.valueOf(c);

}

/*
 * 生成字符串数组
 */public static String  generateString(int l,int s,int n) throws Exception {


if(l<5) {
throw new Exception("字符串的长度应该大于5");
}
if (l < (s+n)) {
throw new Exception("字符串中指定的数字和特殊符号的个数不正确");
}
if (s < 0||n<0 ) {
throw new Exception("特殊符号和数字的个数必须为0或者或大于0的 正整数 ");
}

String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String symbos="!@#$%^&*()_+=<>?";
String numbers="0123456789";
Random random = new Random();

char[] randomString = new char[l];

for (int i = 0; i < (l - n - s); i++) {
randomString[i]=chars.toCharArray()[random.nextInt(chars.length())];
}

for (int i = 0; i < s; i++) {
randomString[i + (l-n-s)] = symbos.toCharArray()[random.nextInt(symbos.length())];
}

for (int i = 0; i < n; i++) {
randomString[i+(l-n)]=numbers.toCharArray()[random.nextInt(numbers.length())];
}
return shuffle(randomString);
}


}

有什么改进的建议?  

文章来源:智云一二三科技

文章标题:初学Java,写了一个生成随机密码方法

文章地址:https://www.zhihuclub.com/187510.shtml

关于作者: 智云科技

热门文章

网站地图