aspose file tools
The moose likes Beginning Java and the fly likes random strings Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Mongo DB Applied Patterns this week in the MongoDB forum
or a resume review from Five Year Itch in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "random strings" Watch "random strings" New topic
Author

random strings

Manuel Diaz
Ranch Hand

Joined: Apr 22, 2005
Posts: 79
HI, what method can I use to chose random strings and print it to the screen. Here is my actual code:

final String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random generator = new Random();
int number;

for (int count = 1;count<=3;count++)
{
c.print(generator.nextInt(3));
}

Im generating three numbers, but I dont know what can I use to generate three random letters, I need to chose my letters from my variable LETTERS. Generating numbers is easy but im stuck with strings, I dont know how to access the variable, read it and then generate the random chose.

Thank you.


Note: I love programming.
K Riaz
Ranch Hand

Joined: Jan 08, 2005
Posts: 375
Generate a number between 0 and 25 inclusive, then use charAt() to pick a letter from your LETTERS variable.

e.g. LETTERS.charAt(r.nextInt(LETTERS.length()));
[ April 23, 2005: Message edited by: Kashif Riaz ]
Manuel Diaz
Ranch Hand

Joined: Apr 22, 2005
Posts: 79
e.g. LETTERS.charAt(r.nextInt(LETTERS.length()));

Thank you very much, it helps me!.

BYE
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I like to use an alphabet with no vowels for this stuff. It helps to avoid generating offensive words. Sometimes I mix in digits and also leave out 1 & 0 because they're too easy to confuse with I and O in some fonts.

Another good trick is to take a random number and use Integer to convert it to base 36. You might have to truncate or concatenate several results to get the right length. And you get the vowels back doing that.
[ April 24, 2005: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: random strings
 
Similar Threads
Three random numbers not working
Generating random letters
Creating random Unique values
Unique 8-length chars algorithm
String > Integer