输入:密码的长度n
输出:随机密码,其中生成的随机密码必须包含大写字母,小写字母和数字。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Main {
static final char[] low = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s'
,'t','u','v','w','x','y','z'};
static final char[] high = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N'
,'O','P','Q','R','S','T','U','V','W','X','Y','Z'};
static final char[] num = {'0','1','2','3','4','5','6','7','8','9'};
private static char getRandomChar(char[] str) {
Random r = new Random();
return str[r.nextInt(str.length)];
}
private static char getLowChar() {
return getRandomChar(low);
}
private static char getUpperChar() {
return Character.toUpperCase(getLowChar());
}
private static char getNumChar() {
return getRandomChar(num);
}
private static char getRandomChar(int funNum) {
switch (funNum) {
case 0:
return getLowChar();
case 1:
return getUpperChar();
default:
return getNumChar();
}
}
public static String get(int len){
List list = new ArrayList<>(len);
list.add(getLowChar());
list.add(getUpperChar());
list.add(getNumChar());
for (int i = 3; i < len; i++) {
Random r = new Random();
int n = r.nextInt(3);
list.add(getRandomChar(n));
}
Collections.shuffle(list);
StringBuilder ans = new StringBuilder(list.size());
for (Character c : list) {
ans.append(c);
}
return ans.toString();
}
public static void main(String[] args) {
System.out.println(get(5));
}
}