随机生成数字、随机密码

1、随机生成0-9的数字

int firstNum = 0;
int secondNum = 0;
int thirdNum = 0;
Random r = new Random();
for (int i = 1; i < 4; i++) {
int num = r.nextInt(10); // 生成[0,9]区间的整数
if (i == 1){
firstNum = num;
}else if (i == 2){
secondNum = num;
}else if (i == 3){
thirdNum = num;
}
}

2、随机生成密码 包括大小写字母、数字、特殊字符

@GetMapping("/test")
public R test() {
String pd=this.getRandomPassword(6);
return R.data(pd);
}

public String getRandomPassword(int len) {
String result = null;
while(len>=6){
result = this.makeRandomPassword(len);
if (result.matches(".*[a-z]{1,}.*") && result.matches(".*[A-Z]{1,}.*") && result.matches(".*\\d{1,}.*") && result.matches(".*[~!@#$%^&*\\.?]{1,}.*")) {
return result;
}
result = makeRandomPassword(len);
}
return "长度不得少于6位!";
}
public String makeRandomPassword(int len){
char charr[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*.?".toCharArray();
StringBuilder sb = new StringBuilder();
Random r = new Random();
for (int x = 0; x < len; ++x) {
sb.append(charr[r.nextInt(charr.length)]);
}
return sb.toString();
}

posted @   宁静暖风  阅读(466)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示