Generating a random character out of any two in Java

后端 未结 4 1752
太阳男子
太阳男子 2021-01-23 08:32

How do I generate a random character between two specific characters? For e.g; I want to generate either one of \'h\' or \'v\'.

Thanks

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-23 08:58

    If you want to generate a character, as you say, either h or v, you can generate a random number using the Random class as shown here. If for instance the random number is greater than 0.5, then choose v, if otherwise, choose h.

    On the other hand, if you have a range of letters, you can either generate an array with the characters you want and generate a random number which will be used as an index to choose the random letter, or else, you can generate random number between 65 (Aschii for A) and 90 (Aschii for Z). You can find more Aschii characters here

提交回复
热议问题