Java工具類_隨機生成任意長度的字符串【密碼、驗證碼】

import java.util.Random;

public class PasswordCreate {
    /** 
     * 獲得密碼 
     * @param len 密碼長度 
     * @return 
     */
    public String createPassWord(int len) {
        int random = this.createRandomInt();
        return this.createPassWord(random, len);
    }

    public String createPassWord(int random, int len) {
        Random rd = new Random(random);
        final int maxNum = 62;
        StringBuffer sb = new StringBuffer();
        int rdGet;//取得隨機數  
        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', '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' };

        int count = 0;
        while (count < len) {
            rdGet = Math.abs(rd.nextInt(maxNum));//生成的數最大爲62-1  
            if (rdGet >= 0 && rdGet < str.length) {
                sb.append(str[rdGet]);
                count++;
            }
        }
        return sb.toString();
    }

    public int createRandomInt() {
        //得到0.0到1.0之間的數字,並擴大100000倍  
        double temp = Math.random() * 100000;
        //如果數據等於100000,則減少1  
        if (temp >= 100000) {
            temp = 99999;
        }
        int tempint = (int) Math.ceil(temp);
        return tempint;
    }

    public static void main(String[] args) {
        PasswordCreate pwc = new PasswordCreate();
        System.out.println(pwc.createPassWord(6));
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章