开发者

How can I generate a unique random number each time when I run my application? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. 开发者_开发百科

Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist

Closed 9 years ago.

Improve this question

In my application, i want to generate 9 digit random numbers such that they r unique. Only one 9 digit random number should be generated each time i run the application and it should be unique. Later i want to save this number along with its associated data in a .txt file so that i can retrive the data associated with this unique number when required. How should i achieve this?


Do you want them to be truly random or truly unique? You can only have one of these.

If you want them to be truly random, then just randomly pick 9 digits from 0-9 and construct them into your number. There will be a small chance of a duplication, especially over larger numbers of iterations. It will be truly random, though.

If you want them to be truly unique, then you have to store every one in a database to ensure there are no duplicates. If you generate a duplicate, you'll need to regenerate or just increment the number and try again. If this is what you're looking for, it might be good to try just incrementing the value starting at one.


For unique number try: (new Date()).getTime() it will never be the same unless you are generating multiple number in a sec.


You could combine the Random Class & system time (or a function using system time) e.g.

  Random random = new Random(System.nanoTime());

  int randomInt = random.nextInt(1000000000);

You could also use some function on the system time e.g.

  Random random = new Random(System.nanoTime() % 100000);

  int randomInt = random.nextInt(1000000000);


If you just want a random 9-digit number, try:

long number = (long) Math.floor(Math.random() * 900000000L) + 10000000L;

However, if you just want an unique number I'd go for using a database instead.


What you're asking for is a unique identifier, that can never be repeated, this is by definition not a random number.

What you're probably looking for are GUIDs, but these are a lot longer than 9 digits (because the chance on generating the same number twice with only 9 digits is quite large if you look at it from a global scale).

Anyway check this wikipedia article: http://en.wikipedia.org/wiki/Globally_unique_identifier

Edit: to clarify, GUIDs have somewhate of a random nature.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜