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条回答
何必那么认真
2楼-- · 2019-02-12 00:29
char randomLetter = (char) ('a' + Math.random() * ('z'-'a' + 1));
查看更多
我命由我不由天
3楼-- · 2019-02-12 00:46

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.

查看更多
登录 后发表回答