JAVA:将输入存储到数组中

发布于 2024-09-05 08:04:07 字数 524 浏览 5 评论 0原文

我需要编写一个程序,该程序将生成随机字母,并且我需要将这个随机字符存储到数组中,

        char[] arrayRandom = new char[10];


        for (int i = 0; i < 8; i++) {
            randomNumLet = (generator.nextInt(20) + 1);
            System.out.print(arrayRandomLetter[randomNumLet] + " ");
            arrayRandomLetter[randomNumLet] = arrayRandom[i];
        }

我的代码有什么问题吗? 因为当我运行它并打印数组时,我得到数组中所有值的框,并且有一些字母这行代码无法打印

            System.out.print(arrayRandomLetter[randomNumLet] + " ");

谢谢

I need to write a program where the program would generate random letter and i would need to store this random character into an array

        char[] arrayRandom = new char[10];


        for (int i = 0; i < 8; i++) {
            randomNumLet = (generator.nextInt(20) + 1);
            System.out.print(arrayRandomLetter[randomNumLet] + " ");
            arrayRandomLetter[randomNumLet] = arrayRandom[i];
        }

is there anything wrong with my code?
because when i run this and printed the array i get boxes for all the values in the array and there are some letter that this line of code cannot print

            System.out.print(arrayRandomLetter[randomNumLet] + " ");

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

因为看清所以看轻 2024-09-12 08:04:07

您正在为 arrayRandomLetter 的元素分配 arrayRandom 中的值。由于您从未初始化arrayRandom,因此它的值都是 0。0 不是可打印字符的值,因此是方框。

选择随机字符的一个简单方法如下:

String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char randomChar = chars.charAt(random.nextInt(chars.length()));

You're assigning an element of arrayRandomLetter a value from arrayRandom. As you never initialize arrayRandom, its values are all 0. 0 is not the value of a printable character, hence the boxes.

An easy way to pick a random character is like this:

String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char randomChar = chars.charAt(random.nextInt(chars.length()));
翻了热茶 2024-09-12 08:04:07

您正在尝试在分配 arrayRandomLetter 之前打印它。

You are trying to print arrayRandomLetter before it is assigned.

杯别 2024-09-12 08:04:07

我不会给你答案,但我会给你一个提示:

(char)('A' + 1) is 'B'

@fastcodejava 的答案解释了为什么你会看到“盒子”——渲染 ASCII NUL 字符。

@Mark Peters 也是正确的,但这不是最简单的解决方案。

I'm not going to give you the answer, but I will give you a hint:

(char)('A' + 1) is 'B'

@fastcodejava's answer explains why you are seeing "boxes" -- rendering the ASCII NUL character.

@Mark Peters is also correct, but that's not the simplest solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文