如何在java中生成一个15位长的随机数

时间:2012-12-14 09:56:12

标签: java random

  

可能重复:
  Java random number with given length

我一直试图在java中生成一个15位长的数字,但似乎我没有使用它做到这一点:

这最多可产生10位数字。

  Random random = new Random();
  int rand15Digt = random.nextInt(15);

如何成功生成它?

5 个答案:

答案 0 :(得分:5)

使用Random的方法public long nextLong()

答案 1 :(得分:3)

首先,int可以在-2,147,483,6482,147,483,647之间保留数字。

使用Random.nextLong()

答案 2 :(得分:1)

当以字符串形式显示时,任何数字都可以格式化为15位十进制数字。这是在将数字转换为字符串时实现的,例如:

System.out.println(String.format("%015d", 1));

// prints: 000000000000001

如果要生成介于100,000,000,000,000999,999,999,999,999之间的随机数,则可以perform a trick,例如:

Random random = new Random();    
long n = (long) (100000000000000L + random.nextFloat() * 900000000000000L);

如果您的最终目标是使用包含随机十进制数字的15个字符的字符串,并且您对第三方库感到满意,请考虑Apache commons RandomStringUtils

boolean useLetters = false;
boolean useNumbers = true;
int stringLength = 15;

String result = RandomStringUtils.random(stringLength, useLetters, useNumbers) 

答案 3 :(得分:1)

如何尝试BigInteger,请参阅此StackOverflow链接以获取更多信息Random BigInteger Generation

答案 4 :(得分:0)

在Hibernate中使用UUIDGenerator类,我们也可以创建安全随机数和唯一数。

public Serializable generate(SessionImplementor session, Object object)
        throws HibernateException {
    String uuid = (String)super.generate(session, object);
    return uuid.substring(uuid.length()-15, uuid.length());
}

我认为这是生成唯一且随机数的最佳方式......