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

2019-02-11 23:52发布

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?

标签: java random
8条回答
Juvenile、少年°
2楼-- · 2019-02-12 00:19
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);
}
查看更多
唯我独甜
3楼-- · 2019-02-12 00:22

use the ascii value of the letters to generate the random number.

查看更多
Bombasti
4楼-- · 2019-02-12 00:24

alter version of @Michael Barker

    Random r = new Random();
    int c = r.nextInt(26) + (byte)'a';
    System.out.println((char)c);
查看更多
Anthone
5楼-- · 2019-02-12 00:26
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
...
randomAlphabetic(1).toLowerCase()

this gives you a string with single character

查看更多
虎瘦雄心在
6楼-- · 2019-02-12 00:27

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.

查看更多
干净又极端
7楼-- · 2019-02-12 00:29
Random r = new Random();
char c = (char) (r.nextInt(26) + 'a');
查看更多
登录 后发表回答