Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Creating an autogenerate number in java

 
Rekha Subramaniyan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I want to create a autogenerated number with customized. It should have
7 numbers long. The first 2 digits should be like 08-- it may changes over the year.. and the next 1 digit --- 1 or 2 depends on the checkbox selection and the last four digits should be autogenerated.. Any help..

Regards,
Rekha
 
Henry Wong
author
Marshal
Pie
Posts: 21115
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds straightforward. What have you done so far? Care to show us some code?

Henry
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Should it remain unique among JVMs as well? And if you restart the JVM?

If so, you will have to store the last created unique part somewhere - in a file, a database, or the Windows registry (using java.util.Preference for instance). Because even classes like UUID will not create unique numbers among JVMs.
 
Sunil Chandurkar
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For each randomly generated digit I would do this:

int a = (int) (Math.random()*10);

int b = (int) (Math.random()*10);

String aString =String.valueOf(a);

String bString =String.valueOf(b);

aString+bString will give you a two digit random number.

You can convert a String to a number again if you want by
int i = Integer.parseInt(aString);
double d = Double.parseDouble(aString);

Hope this helps.
 
Campbell Ritchie
Sheriff
Posts: 48930
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That would create random Strings, Sunil, but it wouldn't sort out Rob's problem about uniqueness.
I would go for Rob's text file solution as being the simplest and possibly giving more portability than using the Registry.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But if you use java.util.Preference that will also work on all systems. The only difference is in how it is implemented; Mac and Linux probably use text files.
 
Campbell Ritchie
Sheriff
Posts: 48930
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Rob; I had misunderstood your previous post about the Registry.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic