随机生成数字、随机密码
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();
   }

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号