标签:return chars rnd char nextInt length 随机数 工具 生成
import java.util.Random;
/**
* @ClassName RandomUtils.java
* @Description 随机数生成
*/
public class RandomUtils {
private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";
/**
* 查找一个char数组中还没有填充字符的位置
*/
private static int nextIndex(char[] chars, Random rnd) {
int index = rnd.nextInt(chars.length);
while (chars[index] != 0) {
index = rnd.nextInt(chars.length);
}
return index;
}
/**
* 返回一个随机的特殊字符
*/
private static char nextSpecialChar(Random rnd) {
return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
}
/**
* 返回一个随机的大写字母
*/
private static char nextUpperLetter(Random rnd) {
return (char) ('A' + rnd.nextInt(26));
}
/**
* 返回一个随机的小写字母
*/
private static char nextLowerLetter(Random rnd) {
return (char) ('a' + rnd.nextInt(26));
}
/**
* 返回一个随机的数字
*/
private static char nextNumLetter(Random rnd) {
return (char) ('0' + rnd.nextInt(10));
}
/**
* 返回一个随机的字符
*/
private static char nextChar(Random rnd) {
switch (rnd.nextInt(3)) {
case 0:
return (char) ('a' + rnd.nextInt(26));
case 1:
return (char) ('A' + rnd.nextInt(26));
default:
return (char) ('0' + rnd.nextInt(10));
}
}
/**
* 返回一个随机的字符(包含特殊字符)
*/
private static char nextCharWithSpecialChars(Random rnd) {
switch (rnd.nextInt(4)) {
case 0:
return (char) ('a' + rnd.nextInt(26));
case 1:
return (char) ('A' + rnd.nextInt(26));
case 2:
return (char) ('0' + rnd.nextInt(10));
default:
return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
}
}
/**
* 生成指定位数的随机数
* @param length 长度
* @param containSpecialChars 是否包含特殊字符
*/
public static String randomChars(int length, boolean containSpecialChars){
char[] chars = new char[length];
Random rnd = new Random();
//1. 填补空白位置的字符
for (int i = 0; i < length; i++) {
if (chars[i] == 0) {
chars[i] = (containSpecialChars ? nextCharWithSpecialChars(rnd) : nextChar(rnd));
}
}
//2. 返回结果
return new String(chars);
}
/**
* 生成指定位数的随机密码
* @param length 长度
*/
public static String randomPassword(int length) {
if(length < 4){
return "";
}
char[] chars = new char[length];
Random rnd = new Random();
//1. 至少生成一个大写字母、小写字母、特殊字符、数字
chars[nextIndex(chars, rnd)] = nextSpecialChar(rnd);
chars[nextIndex(chars, rnd)] = nextUpperLetter(rnd);
chars[nextIndex(chars, rnd)] = nextLowerLetter(rnd);
chars[nextIndex(chars, rnd)] = nextNumLetter(rnd);
//2. 填补其他位置的字符
for (int i = 0; i < length; i++) {
if (chars[i] == 0) {
chars[i] = nextCharWithSpecialChars(rnd);
}
}
//3. 返回结果
return new String(chars);
}
}
标签:return,chars,rnd,char,nextInt,length,随机数,工具,生成 来源: https://www.cnblogs.com/xfeiyun/p/15770619.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。