Haugens
Haugens

Reputation: 1

Three specific letters random generated from array

I really want to make a class that can generate 3 random letters with an array 12 times. I'm having some trouble with random requesting int instead of char. Thanks for help! :)

Upvotes: 0

Views: 113

Answers (2)

Hedegare
Hedegare

Reputation: 2047

You can use ASCII codes to convert a random integer number to the correspondent char. More info about ascii at: http://www.ascii-code.com/

This simple method outputs a char based on a random integer between 65 (capital A) and 90 (capital Z).

public char randomChar(){
    Random r = new Random();
    int num = r.nextInt(26) + 65;
    return (char) num;
}

Now you can tweak this method to your own purposes.

Upvotes: 0

thatguy
thatguy

Reputation: 22089

First, you need to define an alphabet String alphabet = "AaBb...", which contains all valid characters. Then your code can look like this:

public char generateRandomLetterFromAlphabet(String alphabet) {
    Random random = new Random();
    return alphabet.charAt(random.nextInt(alphabet.length()));
}

Here, nextInt(alphabet.length()) returns a random index between zero and the length of the alphabet string, so a random character of your alphabet is returned by generateRandomLetterFromAlphabet. Note that Random generates pseudo-random numbers.

Of course, your alphabet can be defined by an array, too. Here you have a function to generate a specified number of random characters from an alphabet as character array:

public char[] generateRandomLettersFromAlphabet(char[] alphabet,
        int numberOfLetters) {

    if (numberOfLetters < 1) {
        throw new IllegalArgumentException(
                "Number of letters must be strictly positive.");
    }

    Random random = new Random();
    char[] randomLetters = new char[numberOfLetters];

    for (int i = 0; i < numberOfLetters; i++) {
        randomLetters[i] = alphabet[random.nextInt(alphabet.length)];
    }

    return randomLetters;

}

Upvotes: 2

Related Questions