How to record the generation of random letters?
- what letters? Russian or English alphabet? - Artem Konovalov
|
2 answers
You can create an array of char[] , which will store all kinds of characters that can be generated.
Further, using a pseudo-random number generator to get some pseudo-random number from the range from zero to char[].length - 1 .
And then just take from the array char[] character at the resulting 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 .
|
Receiving random letters, excluding the alphabet
private static char getRandom() { Random random = new Random(); int codePoint; while (!Character.isAlphabetic(codePoint = random.nextInt(Short.MAX_VALUE * 2))) ; return (char) codePoint; } |