如题所要求,编写一个对应的方法实现数字与字符指定数目的随机组合,示例代码如下所示:
方法一:
/**
* 0~9 a~z A~Z 随机字符串生成器
*
* @param scale
* 字符串长度
* @param count
* 字符串数量
* @return 结果集合
* @date 2020-03-28 19:38:07
*/
public static List<String> RandomStr(int scale, int count) {
StringBuilder sb = new StringBuilder();
String strNum = "0123456789";
String strCh = "abcdefghijklmnopqrstuvwxyz";
sb.append(strNum).append(strCh).append(strCh.toUpperCase());// 0~9 a~z A~Z
List<String> res = new ArrayList<String>();
int index = 0;
char[] ch = new char[scale];
while (0 != count--) {
for (int i = 0; i < ch.length; i++) {
index = (int) (Math.random() * sb.length());// 生成0 到 sb.length()-1的随机数
ch[i] = sb.charAt(index);
}
res.add(String.valueOf(ch));
}
return res;// 大小为count
}
public static void main(String[] args) {
List<String> list = RandomStr(6, 10);
System.out.println(list);
}
方法二:
可使用工具类:RandomStringUtils(org.apache.commons.lang3.RandomStringUtils)
maven依赖:
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
详细用法可参考博客:https://blog.csdn.net/zhuzj12345/article/details/84324350