工具类之随机数

有的时候项目可能需要随机数,就简单的写了个产生随机数的的工具类
以下是代码

import java.util.Random;

public class RandomUtil {
    /**
     * 待选随机数值
     */
    private static final String RANDOM_SET = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
    /**
     * 数字随机数待选值
     */
    private static final String DIGIT_SET = "1234567890";
    /**
     * 字母随机数待选值
     */
    private static final String LETTER_SET = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";

    /**
     * 用户可选择的添加产生随机数的样本 默认为大小写字母和数字
     */
    private static  String chosen_set = RANDOM_SET;
    /**
     * 产生随机数的类型
     * 0 : 包含大小写字母和数字
     * 1 : 只包含字母
     * 2 : 只包含数字
     */
    private static final int DEFAULT_SET = 0;
    private static final int LETTER_TYPE = 1;
    private static final int DIGIT_TYPE = 2;

    private RandomUtil(){}

    /**
     * 随机产生一个定长的字符串只包含大小写字母及数字,
     *
     * @param len 随机数的长度
     * @return 定长的随机字符串
     */
    public static String RandomDigitAndLetter(int len) {
       return RandomStr(RANDOM_SET,len);
    }

    public static String RandomStr(int type, int len) {
        if (type == DEFAULT_SET) {
            return RandomDigitAndLetter(len);
        }

        if (type == LETTER_TYPE) {
            return RandomLetter(len);
        }

        if (type == DIGIT_TYPE) {
            return RandomDigit(len);
        }

        throw new RuntimeException("无此type" + type);
    }

    public static String RandomDigit(int len) {
        return RandomStr(DIGIT_SET,len);
    }

    public static String RandomLetter(int len) {
        return RandomStr(LETTER_SET,len);
    }

    /**
     * 根据传入的字符串的字符生成随机数
     * @param len 随机数的长度
     * @return 根据传入的字符串的字符生成随机数
     */
    public static String RandomStr(String strSet , int len){
        chosen_set = strSet;
        StringBuffer randomStr = new StringBuffer();
        Random r = new Random();
        for (int randomIndex = 0;  randomIndex< len ; randomIndex++) {
            randomStr.append(chosen_set.charAt(r.nextInt(chosen_set.length())));
        }
        return randomStr.toString();
    }

    public static void main(String[] args) {
        System.out.println(RandomUtil.RandomStr(2,9));
        System.out.println(RandomUtil.RandomDigitAndLetter(6));
        System.out.println(RandomUtil.RandomLetter(6));
        System.out.println(RandomUtil.RandomDigit(6));
        String chosen_set = "@!$#%^+-.,/qscf543";
        System.out.println(RandomUtil.RandomStr(chosen_set,6));
    }
}

结果:

302326493
WCaY7X
lDJLUI
607399
sc+@,.

对于这方面不太熟悉的朋友可以了解一下。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值