• java生成随机数、随机英文字母、随机字符串


    1.生成随机数字

    以生成4位随机数字举例说明

    方式一:

    (int) (Math.random() * (9999 - 1000 + 1)) + 1000

    说明:

    随机数范围:1000~9999。

    方式二:

    new Random().nextInt(9999 - 1000 + 1) + 1000

    说明:

    随机数范围:1000~9999。

    方式三:

    String.format("%04d",new Random().nextInt(9999 + 1))

    说明:

    随机数范围:0000~9999。

    方式四:推荐使用

    所需jar包

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.12.0</version>
    </dependency>

    生成任意长度的随机数字

    RandomStringUtils.randomNumeric(length)

    2.生成随机英文字母

    也是使用common-lang3.jar

    生成任意长度的随机英文字母

    RandomStringUtils.randomAlphabetic(length)

    说明:

    随机字母范围:[a,Z],即26个小写英文字母+26个大写英文字母(区分大小写)。

    3.生成随机字符串

    方式一:

    /*
     * 生成随机字符串
     * @description:
     * @date: 2022/4/20 11:18
     * @param: len 随机字符串的长度
     * @return: java.lang.String 指定长度的随机字符串
     */
    public static String genRandomStr(int len) {
        // 35是因为数组是从0开始的,26个字母+10个数字
        final int maxNum = 36;
        int i; // 生成的随机数
        int count = 0; // 生成的随机数的长度
        char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
                't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    
        StringBuilder pwd = new StringBuilder();
        Random r = new Random();
        while (count < len) {
            // 生成随机数,0~35
            i = r.nextInt(maxNum);
    
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
    
        return pwd.toString();
    }

    方式二:推荐使用

    生成任意长度的随机字母+随机数字

    RandomStringUtils.randomAlphanumeric(length);

    说明:

    随机字母范围:[a,Z],即26个小写英文字母+26个大写英文字母(区分大小写)。

    写在最后

      哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

     相关推荐:

  • 相关阅读:
    Android手机资料拷贝导出工具 --- 91手机助手
    Adobe Acrobat Reader DC For Android 下载
    How to install Wine on Ubuntu Linux 64bit
    Ubuntu 最好用的CHM阅读器KchmViewer
    精品绿色便携软件 & 录制操作工具
    windows 电脑配置信息检测
    彻底理解android中的内部存储与外部存储
    Web标准颜色 System.Drawing.Color
    傲游浏览器---自定义 UserAgent 字符串
    Android direct-boot
  • 原文地址:https://www.cnblogs.com/Marydon20170307/p/16329653.html
Copyright © 2020-2023  润新知