java生成必须包含字母、数字和特殊字符(610位)的随机字符串
我正在生成一个6到10位数的密码
这是我的密码,给我6-10位的随机密码
val AB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:<=>?@_!#%&()*+,-.~";
val rnd = new Random();
def randomPassword(): String = {
val len = rnd.nextInt(5) + 5
val sb = new StringBuilder(len);
for (i <- 0 to len)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
它工作正常,但问题是,有时它会给出所有的数字或字母
我每次都想要字母、数字和特殊字符的组合。有什么建议吗
# 1 楼答案
下面是一个更惯用的解决方案,它提供了更好的API
让我们生成一些密码
你会看到类似的东西
注意:此解决方案可以进行几轮优化。例如
@tailrec
,StringBuilder
# 2 楼答案
首先生成所有字母的随机密码,然后根据需要将部分字母替换为数字/特殊字符
(顺便说一句,我不熟悉Scala,所以我将使用Java的语法,因为我不知道键入的内容是否有效。很抱歉。)
这是一个开始,有一个缺陷(只有一个数字+特殊字符),但很容易修复。如果一个密码不满足您的条件,此解决方案也比生成全新密码更有效,并且您可以保证在方法返回时获得一个有效的密码
# 3 楼答案
# 4 楼答案
使用不可变数据结构对scala来说更为惯用。下面的代码可以工作
编辑: 为了确保字符串中始终有数字、特殊字符和字母表,我将分别生成每一类字母,然后以函数方式或简单地使用Random随机连接它们。洗牌(字符列表)。mkString=D
# 5 楼答案
您可以应用while循环的原理