Java中生成一个随机字符串

生成随机数的方法

Java中生成随机数的方法常用的有Math.random()random.nextInt().

Math.random() 是一个静态方法,方法生成[0, 1)范围内的double类型随机数,而且,这个方法是线程安全的。如果想用Math.random()生成随机整数,可以使用(int)(Math.random()*n)的方法生成 [0, n) 的整数。

Random类的public int nextInt(int bound)方法返回伪随机的均匀分布的 [0, bound) 之间的整数。下面是Java对这个方法的定义,从定义中可以发现,bound只能是正数。

public int nextInt(int bound) {
    if (bound <= 0)
        throw new IllegalArgumentException(BadBound);

    int r = next(31);
    int m = bound - 1;
    if ((bound & m) == 0)  // i.e., bound is a power of 2
        r = (int)((bound * (long)r) >> 31);
    else {
        for (int u = r;
             u - (r = u % bound) + m < 0;
             u = next(31))
            ;
    }
    return r;
}

Random类中的nextInt()方法生成的随机数有正有负,且绝对值很大。

生成随机字符串示例

下面的两个方法分别演示如何生成n位随机数和n位数字和字母的随机组合。

/**
 * 生成n位随机数字
 * @param n 随机数的数字位数
 * @return n位数字组成的随机数字字符串
 */
public static String getRandomNumStr(int n) {
    Random random = new Random();
    StringBuilder randomStr = new StringBuilder();
    for (int i = 0; i < n; i++) {
        randomStr.append(random.nextInt(10));
    }
    return randomStr.toString();
}
/**
 * 生成n位随机数字和字母
 * @param n 随机字符的位数
 * @return n位数字和字母组成的随机字符串
 */
public static String getRandomCharStr(int n) {
    String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Random random = new Random();
    StringBuilder randomStr = new StringBuilder();
    for (int i = 0; i < n; i++) {
        randomStr.append(codes.charAt(random.nextInt(62)));
    }
    return randomStr.toString();
}

使用上面生成数字和字母的方法生成的随机字符串中,数字少,字母多,一种最简单的处理方法就是在codes字符串中增加数字的数量。

如果对数字或者字母的个数有要求,甚至如果有特殊字符的要求,就应该分别生成。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值