Monday, February 14, 2011

How to generate random letters in Java

I know there is a java.util.Random class, which provides more flexible ways to generate uniformly distributed random numbers, like:
Random r = new Random();
int i = r.nextInt(int n) Returns random int >= 0 and < i =" r.nextInt()" l =" r.nextLong()" f =" r.nextFloat()">=0.0 and < d =" r.nextDouble()">=0.0 and < 1.0.
boolean b = r.nextBoolean() Returns random boolean (true or false).

But how can you generate random letters for a string?
Here are solutions:

Solution 1:
String q[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

Random r = new Random();
String c = q[r.nextInt(25)]+ q[r.nextInt(25)]+ q[r.nextInt(25)] + q[r.nextInt(25)];

Solution 2: using ASC II integer to string convert
Random r = new Random();
int n = 0;
String c = "";
while (n<4) {
int i = 65 + r.nextInt(25);
String q = new Character ((char)i).toString();
c = c + q;
n++;
}

Solution 3: If you want every time you pick up different letters, you can try this:
String q[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

Random r = new Random();
int n = 0;
String c = "";
while (n < 4) {

int i = r.nextInt(25) + n;
String a = q[i];
q[i] = q[0+n];
n++;
c = c + a;
}