Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

random strings  RSS feed

 
Manuel Diaz
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
K Riaz
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
e.g. LETTERS.charAt(r.nextInt(LETTERS.length()));

Thank you very much, it helps me!.

BYE
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!