java随机生成n数字和字母的组合
时间: 2023-09-13 11:13:59 浏览: 96
下面是一个示例 Java 代码,用于生成指定长度的由数字和字母组成的随机字符串:
```java
import java.security.SecureRandom;
public class RandomStringGenerator {
private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
public static String generateRandomString(int length) {
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = SECURE_RANDOM.nextInt(CHARACTERS.length());
char randomChar = CHARACTERS.charAt(randomIndex);
builder.append(randomChar);
}
return builder.toString();
}
}
```
使用示例:
```java
String randomString = RandomStringGenerator.generateRandomString(10); // 生成10个字符的随机字符串
System.out.println(randomString);
```
输出示例:
```
HNd3YkF7Gq
```
阅读全文