Re4XN Re4XN - 6 months ago 26
Java Question

Generating random strings, missing one letter

I have a small problem when trying to generate a random string with random size (between 3 and 20). I have an array

with all characters from a (lowercase) to Z (uppercase). I then generate a random length
for a second array
, which will be containing some randomly selected chars.

My issue is that the letter 'a' (lowercase) never appears in my randomly generated strings. I think that the mistake might be inside the
loop, but I have failed to see it so far. Maybe it has something to do with
casting or

char[] arr = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
int arrLength = (int) (Math.floor((Math.random() * ((17 - 3) + 1)) + 3));
char[] arr2 = new char[arrLength];
String str = "";

for(int i=0;i<arrLength;i++) {
char num = arr[(int) (Math.floor(Math.random() * (50) + 1))];
arr2[i] = num;


Instead of the magic constant 50 use arr.length (note there are more than 50 characters in the array) and leave out the +1 as it makes the lowest number you can get to 1 and array indices start at 0 in Java.