1 /** 2 * Created by xc on 2019/11/23 3 * 生成随机密码:6位数字 4 */ 5 public class Test7_4 { 6 7 public static void main(String[] args) { 8 System.out.println(randomPassword());//382630 9 } 10 11 public static String randomPassword() { 12 char[] chars = new char[6]; 13 Random rnd = new Random(); 14 for (int i = 0; i < 6; i++) { 15 chars[i] = (char) ('0' + rnd.nextInt(10)); 16 } 17 return new String(chars); 18 } 19 20 }
1 /** 2 * Created by xc on 2019/11/23 3 * 生成随机密码:简单8位 4 * 8位密码,字符可能由大写字母、小写字母、数字和特殊符号组成 5 */ 6 public class Test7_5 { 7 8 private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/"; 9 10 public static void main(String[] args) { 11 System.out.println(randomPassword());//ejgY^14* 12 } 13 14 private static char nextChar(Random rnd) { 15 switch (rnd.nextInt(4)) { 16 case 0: 17 return (char) ('a' + rnd.nextInt(26)); 18 case 1: 19 return (char) ('A' + rnd.nextInt(26)); 20 case 2: 21 return (char) ('0' + rnd.nextInt(10)); 22 default: 23 return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length())); 24 } 25 } 26 27 public static String randomPassword() { 28 char[] chars = new char[8]; 29 Random rnd = new Random(); 30 for (int i = 0; i < 8; i++) { 31 chars[i] = nextChar(rnd); 32 } 33 return new String(chars); 34 } 35 36 }
1 /** 2 * Created by xc on 2019/11/23 3 * 生成随机密码:复杂8位 4 */ 5 public class Test7_6 { 6 7 private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/"; 8 9 public static void main(String[] args) { 10 System.out.println(randomPassword());//Q*82-/zQ 11 } 12 13 private static int nextIndex(char[] chars, Random rnd) { 14 int index = rnd.nextInt(chars.length); 15 while (chars[index] != 0) { 16 index = rnd.nextInt(chars.length); 17 } 18 return index; 19 } 20 21 private static char nextSpecialChar(Random rnd) { 22 return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length())); 23 } 24 25 private static char nextUpperlLetter(Random rnd) { 26 return (char) ('A' + rnd.nextInt(26)); 27 } 28 29 private static char nextLowerLetter(Random rnd) { 30 return (char) ('a' + rnd.nextInt(26)); 31 } 32 33 private static char nextNumLetter(Random rnd) { 34 return (char) ('0' + rnd.nextInt(10)); 35 } 36 37 public static String randomPassword() { 38 char[] chars = new char[8]; 39 Random rnd = new Random(); 40 chars[nextIndex(chars, rnd)] = nextSpecialChar(rnd); 41 chars[nextIndex(chars, rnd)] = nextUpperlLetter(rnd); 42 chars[nextIndex(chars, rnd)] = nextLowerLetter(rnd); 43 chars[nextIndex(chars, rnd)] = nextNumLetter(rnd); 44 for (int i = 0; i < 8; i++) { 45 if (chars[i] == 0) { 46 chars[i] = nextChar(rnd); 47 } 48 } 49 return new String(chars); 50 } 51 52 private static char nextChar(Random rnd) { 53 switch (rnd.nextInt(4)) { 54 case 0: 55 return (char) ('a' + rnd.nextInt(26)); 56 case 1: 57 return (char) ('A' + rnd.nextInt(26)); 58 case 2: 59 return (char) ('0' + rnd.nextInt(10)); 60 default: 61 return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length())); 62 } 63 } 64 65 }