-
Random類:
-
用于生成隨機數
-
import java.util.Random;
導入必要的類
-
-
generateVerificationCode()方法:
-
這是一個靜態方法,可以直接通過類名調用
-
返回一個6位數字的字符串,首位不為0
-
-
生成首位數字:
-
random.nextInt(9) + 1
:-
nextInt(9)
生成0-8的隨機數 -
使用
StringBuilder
構建驗證碼字符串,先添加首位數字
-
-
確保驗證碼的第一位數字不會是0
-
-
生成剩余5位數字:
-
循環5次,生成驗證碼的剩余5位
-
每次從
allChars
中隨機選擇一個字符(可以是數字或字母) -
random.nextInt(allChars.length())
生成一個隨機索引 -
將選中的字符添加到
StringBuilder
中
-
-
返回結果:
-
sb.toString()
將StringBuilder轉換為String并返回?
-
import java.util.Random;public class Main {public static void main(String[] args) {System.out.println(generateVerificationCode());}/*** 生成6位隨機驗證碼(數字+字母),首位不為0且為數字* @return 隨機驗證碼字符串*/public static String generateVerificationCode() {Random random = new Random();// 定義可用字符集String numbers = "0123456789";String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";String allChars = numbers + letters;// 首位必須是數字且不為0int firstDigit = random.nextInt(9) + 1; // 1-9StringBuilder sb = new StringBuilder().append(firstDigit);// 生成剩余5位,可以是數字或字母for (int i = 0; i < 5; i++) {char c = allChars.charAt(random.nextInt(allChars.length()));sb.append(c);}return sb.toString();}
}
運行結果如下: