java生成随机28位字符串
时间: 2024-03-15 20:38:24 浏览: 121
以下是Java生成随机28位字符串的代码示例:
```java
import java.util.Random;
public class RandomStringGenerator {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static final int LENGTH = 28;
public static String generateRandomString() {
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < LENGTH; i++) {
int randomIndex = random.nextInt(CHARACTERS.length());
sb.append(CHARACTERS.charAt(randomIndex));
}
return sb.toString();
}
public static void main(String[] args) {
String randomString = generateRandomString();
System.out.println(randomString);
}
}
```
该代码使用了Random类生成随机数,并使用StringBuilder类构建字符串。其中,CHARACTERS常量包含了所有可能出现在随机字符串中的字符,LENGTH常量指定了随机字符串的长度。
阅读全文