直接上代码如下:
import java.util.Random;
public class PasswordGenerator {
private static final String LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String NUMERIC_CHARACTERS = "0123456789";
private static final String SPECIAL_CHARACTERS = "9876543210";
public static void main(String[] args) {
// 密码长度
int length = 8;
String password = generatePassword(length);
System.out.println("your password: " + password);
}
public static String generatePassword(int length) {
StringBuilder password = new StringBuilder();
Random random = new Random();
// 从不同的字符集中随机选择字符
for (int i = 0; i < length; i++) {
int charSetIndex = random.nextInt(4);
switch (charSetIndex) {
case 0:
password.append(LOWERCASE_CHARACTERS.charAt(random.nextInt(LOWERCASE_CHARACTERS.length())));
break;
case 1:
password.append(UPPERCASE_CHARACTERS.charAt(random.nextInt(UPPERCASE_CHARACTERS.length())));
break;
case 2:
password.append(NUMERIC_CHARACTERS.charAt(random.nextInt(NUMERIC_CHARACTERS.length())));
break;
case 3:
password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
break;
}
}
return password.toString();
}
}
温馨提示:
charAt()
方法返回字符串中指定索引(下标)处的字符。
第一个字符的索引是 0,第二个是 1,...