java随机生成6位验证码,首位不能是0

在Java中,要随机生成一个6位的验证码,其中首位不能为0,可以使用以下代码示例:

java 复制代码
import java.util.Random;

public class VerificationCodeGenerator {
    public static void main(String[] args) {
        System.out.println(generateVerificationCode());
    }

    /**
     * 生成6位随机验证码,首位不为0
     * @return 随机验证码字符串
     */
    public static String generateVerificationCode() {
        Random random = new Random();
        // 首位数字范围1-9
        int firstDigit = random.nextInt(9) + 1;
        // 剩余位数字范围0-9
        StringBuilder sb = new StringBuilder().append(firstDigit);
        for (int i = 0; i < 5; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}

这段代码定义了一个generateVerificationCode方法,它首先随机生成一个1到9之间的数字作为首位(确保首位不是0),然后循环生成剩下的5位数字,每位数字的范围是0到9,最后将这6位数字拼接成一个字符串作为验证码返回。

相关推荐
踩着两条虫7 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB7 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
budingxiaomoli7 小时前
Spring IoC &DI
java·spring·ioc·di
Spider Cat 蜘蛛猫7 小时前
Springboot SSO系统设计文档
java·spring boot·后端
未若君雅裁7 小时前
MySQL高可用与扩展-主从复制读写分离分库分表
java·数据库·mysql
即使再小的船也能远航8 小时前
【Python】安装
开发语言·python
学习中.........8 小时前
从扰动函数的变化,感受红黑树带来的性能提升
java
Irissgwe8 小时前
类与对象(三)
开发语言·c++·类和对象·友元
计算机安禾8 小时前
【c++面向对象编程】第24篇:类型转换运算符:自定义隐式转换与explicit
java·c++·算法
雪度娃娃8 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++