import java.security.SecureRandom;public class RandomStringGenerator {// 定義允許的字符集(大寫字母和數字)private static final String ALLOWED_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";private static final SecureRandom RANDOM = new SecureRandom();/*** 生成 24 位隨機字符串(大寫字母和數字)* @return 24 位隨機字符串*/public static String generate24CharString() {StringBuilder sb = new StringBuilder(24);for (int i = 0; i < 24; i++) {// 從 ALLOWED_CHARACTERS 中隨機選取一個字符int randomIndex = RANDOM.nextInt(ALLOWED_CHARACTERS.length());char randomChar = ALLOWED_CHARACTERS.charAt(randomIndex);sb.append(randomChar);}return sb.toString();}public static void main(String[] args) {// 示例調用String randomString = generate24CharString();System.out.println("生成的 24 位隨機字符串: " + randomString);}
}
方法說明
-
字符集定義
ALLOWED_CHARACTERS
?包含大寫字母?A-Z
?和數字?0-9
,共 36 個字符。
-
隨機數生成器
- 使用?
SecureRandom
?生成安全的隨機數,避免偽隨機性。
- 使用?
-
字符串生成邏輯
- 通過循環 24 次,每次從?
ALLOWED_CHARACTERS
?中隨機選取一個字符,拼接到?StringBuilder
?中。
- 通過循環 24 次,每次從?
生成的 24 位隨機字符串: A1B2C3D4E5F6G7H8I9J0K1L2
?