简体   繁体   中英

In Java how do you randomly select a letter (a-z)?

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?

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

To randomly select a letter from (a- z) I would do the following:

Random rand = new Random();
...
char c = rand.nextInt(26) + 'a';

Since Random.nextInt() generates a value from 0 to 25, you need only add an offset of 'a' to produce the lowercase letters.

使用字母的 ascii 值生成随机数。

Random r = new Random();
char symbel = (char)(r.nextInt(26) + 'a');
if(symbel>='a' && symbel <= 'z') {
    System.out.println("Small Letter" + symbel);
} else {
    System.out.println("Not a letter" + symbel);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM