Java中如何获取随机字母?
我想使用类似
char ch = 'A' + randomNumber ; // randomNumber is int from 0 to 25
But 这会产生“精度损失”编译错误(如果 randomNumber 只是一个字节则相同)来获得随机字母。 我猜想上面的 Unicode 过于简单化了。
这可行,但似乎有点笨拙:
char ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(randomNumber);
我应该怎么做?
I want to get a random letter using something like
char ch = 'A' + randomNumber ; // randomNumber is int from 0 to 25
But that gives "loss of precision" compilation error (same if randomNumber is only a byte).
I guess with Unicode the above is a gross oversimplification.
This works but seems a bit clumsy:
char ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(randomNumber);
How should I do it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
char ch = (char) (new Random().nextInt('Z' - 'A' + 1) + 'A')
您可以将 'A' 和 'Z' 替换为任意字符想要达到更广泛的范围。
char ch = (char) (new Random().nextInt('Z' - 'A' + 1) + 'A')
You may replace 'A' and 'Z' by any character you want to achieve a wider range.
该问题是由于尝试将
int
分配给char
引起的。由于
int
是 32 位,而char
是 16 位,因此分配int
可能会导致精度损失,因此会出现错误消息在编译时显示。The problem is arising from trying to assign an
int
into achar
.Since an
int
is 32-bits andchar
is 16-bits, assigning anint
can potentially lead to a loss of precision, hence the error message is displayed at compile time.如果您知道自己将在适当的范围内,只需投射:
If you know that you're going to be in the appropriate range, just cast:
这个怎么样?丑陋的铸造但没有编译错误。应该生成一个随机大写字母:
How about this? Ugly casting but no compilation errors. Should generate a random capital letter: