Lazy Wolf
Lazy Wolf

Reputation: 97

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 arr with all characters from a (lowercase) to Z (uppercase). I then generate a random length arrLength for a second array arr2, 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 for loop, but I have failed to see it so far. Maybe it has something to do with (int) casting or Math.floor rounding?

    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;
    }

Upvotes: 1

Views: 68

Answers (1)

Henry
Henry

Reputation: 43778

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.

Upvotes: 5

Related Questions