随机产生4位随机码(java)

  • 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并返回
java 复制代码
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;

        // 首位必须是数字且不为0
        int firstDigit = random.nextInt(9) + 1; // 1-9
        StringBuilder 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();
    }
}

运行结果如下:

相关推荐
抠脚小弟15 分钟前
Spring Cache 使用详解:从入门到实战
java·spring
ZGG00325 分钟前
MySQL 索引详解:B+ 树、聚簇索引与最左前缀
java·数据库·mysql
萧瑟余晖34 分钟前
Java深入解析篇五十四之对象模型详解
java·开发语言
张文是假的啊1 小时前
Java | record | Controller逻辑
java·开发语言
勿忘,瞬间1 小时前
Mybatis高阶
java·数据库·mybatis
嘻哈baby2 小时前
Go 函数中的参数为什么不支持默认值?
java·开发语言·jvm
慧都小项2 小时前
MyEclipse 2026:当 Agent、MCP 与 Java 26 进入 Eclipse 工作流
java·eclipse·springboot·copilot·myeclipse
CoderYanger3 小时前
前端基础——JavaScript(基础语法)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展
京师20万禁军教头3 小时前
39面向对象(高级)-设计模式
java·开发语言·设计模式
白山编程大哥4 小时前
Java 迭代器接口详解:从 Iterator 到 ListIterator 的完整指南
java·开发语言·windows