Java中如何获取随机字母?

发布于 2024-08-10 20:45:21 字数 317 浏览 3 评论 0原文

我想使用类似

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

伪心 2024-08-17 20:45:21

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.

べ映画 2024-08-17 20:45:21

该问题是由于尝试将 int 分配给 char 引起的。

由于 int 是 32 位,而 char 是 16 位,因此分配 int 可能会导致精度损失,因此会出现错误消息在编译时显示。

The problem is arising from trying to assign an int into a char.

Since an int is 32-bits and char is 16-bits, assigning an int can potentially lead to a loss of precision, hence the error message is displayed at compile time.

心不设防 2024-08-17 20:45:21

如果您知道自己将在适当的范围内,只需投射:

char ch = (char) ('A' + randomNumber);

If you know that you're going to be in the appropriate range, just cast:

char ch = (char) ('A' + randomNumber);
吲‖鸣 2024-08-17 20:45:21

这个怎么样?丑陋的铸造但没有编译错误。应该生成一个随机大写字母:

int rand = (int) (Math.random() * 100);
int i = 65 + (rand % 26);
char c = (char) i;
System.out.println(c);

How about this? Ugly casting but no compilation errors. Should generate a random capital letter:

int rand = (int) (Math.random() * 100);
int i = 65 + (rand % 26);
char c = (char) i;
System.out.println(c);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文