在Java中从任意两个字符中生成一个随机字符
如何在两个特定字符之间生成随机字符?例如;我想生成“h”或“v”之一。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注意:构造一次 Random 对象并重复使用它;不要每次需要随机数时都重新构造它!
N.B. construct your Random object once and re-use it; don't re-construct it every time you want a random number!
如果您想生成一个字符,如您所说的 h 或 v,您可以使用 Random 类如图 这里。例如,如果随机数大于0.5,则选择v,否则选择h。
另一方面,如果您有一系列字母,您可以生成一个包含所需字符的数组并生成一个随机数,该随机数将用作选择随机字母的索引,或者,您可以生成随机数介于 65(A 的 Aschii)和 90(Z 的 Aschii)之间。您可以在此处找到更多 Aschii 字符
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
怎么样:
how about:
要在两个给定字符之间生成随机字符,您可以执行以下操作:
To generate a random character between two given characters you could do the following: