生成隨機的數字或字母字符串,指定長度


package com.yxb.base.util;

import java.util.Random;

public class RandNumUtil {
    public RandNumUtil() {
    }

    public static String getRandomString(boolean isNum, int length) {
        String[] base = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "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"};
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < length; ++i) {
            int number = false;
            int number;
            if (isNum && i > 0) {
                number = random.nextInt(10);
            } else if (isNum && i == 0) {
                number = random.nextInt(9);
            } else {
                number = random.nextInt(base.length);
            }

            sb.append(base[number]);
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(getRandomString(false, 32));
    }
}

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