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位数字拼接成一个字符串作为验证码返回。

相关推荐
董世昌41几秒前
创建对象的方法有哪些?
开发语言·前端
BD_Marathon2 分钟前
Spring是什么
java·后端·spring
我命由我123455 分钟前
Android 消息机制 - Looper(Looper 静态方法、Looper 静态方法注意事项、Looper 实例方法、Looper 实例方法注意事项)
android·java·android studio·安卓·android jetpack·android-studio·android runtime
Hard but lovely7 分钟前
linux: pthread库---posix线程创建使用接口&&状态
linux·开发语言·c++
月明长歌7 分钟前
【码道初阶】Leetcode138:随机链表的复制:用 HashMap 做深拷贝的标准解法
java·数据结构·算法·leetcode·链表·哈希算法
xingzhemengyou18 分钟前
Python Lock 详解
开发语言·python
.简.简.单.单.11 分钟前
Design Patterns In Modern C++ 中文版翻译 第八章 组合
java·c++·设计模式
yyy(十一月限定版)16 分钟前
C语言——堆
c语言·开发语言·算法
澜莲花17 分钟前
python图色之opencv基础
开发语言·图像处理·python·opencv
喜欢吃燃面17 分钟前
算法竞赛中的数据结构:图
开发语言·数据结构·c++·学习·算法