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个大写英文字母(区分大小写)。

写在最后

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

 相关推荐:

  • 个人主页
  • java 字符串前面补零(byte、short、int、long、BigDecimal)
  • java String字符串

本文来自博客园,作者:Marydon,转载请注明原文链接:javascript:void(0)/p/16329653.html