1. 程式人生 > 其它 >隨機生成數字、隨機密碼

隨機生成數字、隨機密碼

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();
}