If I want to randomly select a letter between a and z, I assume I have to use the Random
class:
Random rand = new Random();
But since this only generates numbers, what do I need to do to apply this to letters?
Here's how to pick a random one: int randomIndex = new Random(). nextInt(array. length); ObjectReturningSomething randomObject = objectArray.
In order to check if a String has only Unicode letters in Java, we use the isDigit() and charAt() methods with decision-making statements. The isLetter(int codePoint) method determines whether the specific character (Unicode codePoint) is a letter. It returns a boolean value, either true or false.
Using randomUUID() util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.
We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.
Random r = new Random();
char c = (char) (r.nextInt(26) + 'a');
Letters, or more exactly, characters, are numbers (from 0 to 255 in extended ascii, 0 to 127 in non-extended). For instance, in ASCII, 'A' (quote means character, as opposed to string) is 65. So 1 + 'A' would give you 66 - 'B'. So, you can take a random number from 0 to 26, add it to the character 'a', and here you are : random letter.
You could also do it with a string, typing "abcdefghijklmnopqrstuvwxyz" and taking a random position in this chain, but Barker solution is more elegant.
alter version of @Michael Barker
Random r = new Random();
int c = r.nextInt(26) + (byte)'a';
System.out.println((char)c);
char randomLetter = (char) ('a' + Math.random() * ('z'-'a' + 1));
why assume to use Random instead of Math.random? You can even make the code shorter...
public static char genChar(){
return (char)(Math.random()*26 + 'a');
}
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
...
randomAlphabetic(1).toLowerCase()
this gives you a string with single character
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With