java 怎么生成8位同时存在大小写字母和数字的随机密码
时间: 2023-12-10 21:39:27 浏览: 117
JAVA编程实现随机生成指定长度的密码功能【大小写和数字组合】
你可以使用以下代码生成8位同时存在大小写字母和数字的随机密码:
```java
import java.util.Random;
public class PasswordGenerator {
private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
private static final String NUMBER = "0123456789";
private static final String DATA_FOR_RANDOM_STRING = CHAR_LOWER + CHAR_UPPER + NUMBER;
private static Random random = new Random();
public static void main(String[] args) {
int passwordLength = 8;
String password = generateRandomPassword(passwordLength);
System.out.println("Random Password: " + password);
}
private static String generateRandomPassword(int length) {
if (length < 1) {
throw new IllegalArgumentException("Password length must be at least 1.");
}
StringBuilder sb = new StringBuilder(length);
// Generate random characters
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(DATA_FOR_RANDOM_STRING.length());
char randomChar = DATA_FOR_RANDOM_STRING.charAt(randomIndex);
sb.append(randomChar);
}
return sb.toString();
}
}
```
这个代码使用了一个包含了小写字母、大写字母和数字的字符串常量,然后使用 `Random` 类生成随机数来从字符串中选取字符,最终生成一个随机密码。
阅读全文