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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13876322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:17:25  来源:igfitidea点击:

How can I generate a random 15 digit-long in java

javarandom

提问by guthik

Possible Duplicate:
Java random number with given length

可能的重复:
具有给定长度的 Java 随机数

I have been trying to generate a 15 digit long number in java but it seems I have failed to do it so far as using:

我一直在尝试在 Java 中生成一个 15 位长的数字,但到目前为止,我似乎未能做到:

This is producing a maximum of 10 digits.

这将产生最多 10 位数字。

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

How can I generate it successfully?

我怎样才能成功生成它?

回答by StanislavL

Use Random's method public long nextLong()

使用Random的方法 public long nextLong()

回答by SJuan76

To begin with, an intcan hold numbers between -2,147,483,648and 2,147,483,647.

首先,一个int可容纳之间的数字-2,147,483,6482,147,483,647

Use Random.nextLong()

利用 Random.nextLong()

回答by Duncan Jones

Any number can be formatted into 15 decimal digits when presented as a string. This is achieved when the number is converted to a String, e.g.:

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

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

// prints: 000000000000001

If you want to generate a random number that lies between 100,000,000,000,000and 999,999,999,999,999then you can perform a tricksuch as:

如果要生成介于100,000,000,000,000和之间的随机数,999,999,999,999,999则可以执行以下技巧

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

If your ultimate goal is to have a 15-character string containing random decimal digits, and you're happy with third-party libraries, consider Apache commons RandomStringUtils:

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

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

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

回答by Rahul

What about trying BigInteger, see this StackOverflow link for more information Random BigInteger Generation

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

回答by Java Developer

In Hibernate have UUIDGeneratorclass using this we can create Secure Random and Unique Number also.

在 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());
}

i think this is best way to Generate Unique and also Random Number...

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