Java letter generation

Question:

How to record the generation of random letters?

Answer:

You can create a char[] array that will store all sorts of characters that can be generated.

Then, using a pseudo-random number generator, get some pseudo-random number from the range from zero to char[].length - 1 .

And then just take the character from the char[] array at the received index.

public class Main {
    private static Random sRandom = new Random();
    private static char[] sAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
    private static int sLength = sAlphabet.length;

    public static char getRandomChar() {
        return sAlphabet[sRandom.nextInt(sLength)];
    }

    public static void main(String[] args) {

        for (int i=0; i<10; i++) {
            System.out.println(getRandomChar());
        }
    }
}

You can implement it differently: generate a number in the range from the minimum code of a possible character to the maximum, and then just cast int to char .

Scroll to Top