wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Random String (Hash) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Random String (Hash)" Watch "Random String (Hash)" New topic
Author

Random String (Hash)

Charles OBrien
Greenhorn

Joined: May 23, 2002
Posts: 10
Okay, I am proposed with yet another simple problem.
I am trying to figure out a way to create a random string. This string should be around 12 characters long and can consist of letters and numbers.
The purpose of this hash is to serve as a unique identifier for a user. Simmilar to a session, but different.
[Edit: This is for a servlet]
Any help appreciated.
[ June 11, 2002: Message edited by: Charles OBrien ]
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

why not use the Math.random() function to generate a random number for yourself. Then convert that into a char... concatenate the char's together to make a String.
Remember that Math.random() generates a decimal number between 0 and 1 so you'll need to multiply it by some integer to make it a valid int to be converted to a char.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
java.util.Random provides some more ways to create random numbers.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
I had to do something like this and this is what I did:
1) Create an array of characters of all the valid characters that you want in the generated String.
char[] c = {'A', 'a', 'B', etc...}
2) Generate a random number from zero to 1 less than the length of the char array
3) Use that number as an index into the array to pick a random character
4) Use that character as the first character of your string
5) Repeat 2 and 3, adding the chosen charaacter to your String until you have all that characters you need for your string.
The nice thing about this is that you can control exactly what characters are allowed in your string. We eliminated characters that look too much alike such as the number one and lower-case letter 'L'; zero and the upper case letter 'O'. ( 1 and l ; 0 and O). In some fonts they are identical.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Random String (Hash)