1. 程式人生 > 其它 >java生成隨機數、隨機英文字母、隨機字串

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();
}

寫在最後

  哪位大佬如若發現文章存在紕漏之處或需要補充更多內容,歡迎留言!!!

 相關推薦: