随机产生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();
    }
}

运行结果如下:

相关推荐
我是一只代码狗25 分钟前
springboot中使用线程池
java·spring boot·后端
hello早上好38 分钟前
JDK 代理原理
java·spring boot·spring
PanZonghui43 分钟前
Centos项目部署之Java安装与配置
java·linux
沉着的码农1 小时前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
Mr_Xuhhh1 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华2 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
coding and coffee2 小时前
狂神说 - Mybatis 学习笔记 --下
java·后端·mybatis
千楼2 小时前
阿里巴巴Java开发手册(1.3.0)
java·代码规范
reiraoy2 小时前
缓存解决方案
java
安之若素^2 小时前
启用不安全的HTTP方法
java·开发语言