This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Creating an autogenerate number in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Creating an autogenerate number in java" Watch "Creating an autogenerate number in java" New topic

Creating an autogenerate number in java

Rekha Subramaniyan

Joined: Aug 09, 2008
Posts: 5
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..

Henry Wong

Joined: Sep 28, 2004
Posts: 20057

Sounds straightforward. What have you done so far? Care to show us some code?


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor

Joined: Oct 27, 2005
Posts: 20083

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.

How To Ask Questions How To Answer Questions
Sunil Chandurkar
Ranch Hand

Joined: Jan 09, 2008
Posts: 37
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

Joined: Oct 13, 2005
Posts: 44048
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

Joined: Oct 27, 2005
Posts: 20083

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

Joined: Oct 13, 2005
Posts: 44048
Thank you, Rob; I had misunderstood your previous post about the Registry.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Creating an autogenerate number in java
It's not a secret anymore!