JAVA随机生成六位验证码

使用java语言随机生成六位数的验证码

import java.util.Random;

public class RandomCodeGenerator {
    public static void main(String[] args) {
        // 生成六位数验证码
        String verificationCode = generateVerificationCode(6);
        System.out.println("生成的验证码是: " + verificationCode);  // 打印生成的验证码
    }
    
    // 生成指定长度的验证码的方法
    private static String generateVerificationCode(int codeLength) {
    
        // 定义验证码字符集
        String codeChars = "0123456789";
        StringBuilder verificationCode = new StringBuilder();   // 使用StringBuilder来拼接验证码
       
        // 创建Random对象
        Random random = new Random();
        for (int i = 0; i < codeLength; i++) {  // 循环生成指定长度的验证码
            char randomChar = codeChars.charAt(random.nextInt(codeChars.length()));   // 从字符集中随机选择一个字符
            verificationCode.append(randomChar); // 将选定的字符追加到验证码中
        }
     
        return verificationCode.toString();  // 返回生成的验证码字符串
    }
}

你可能感兴趣的:(java,python,开发语言)