JAVA:将输入存储到数组中
我需要编写一个程序,该程序将生成随机字母,并且我需要将这个随机字符存储到数组中,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在为
arrayRandomLetter
的元素分配arrayRandom
中的值。由于您从未初始化arrayRandom
,因此它的值都是 0。0 不是可打印字符的值,因此是方框。选择随机字符的一个简单方法如下:
You're assigning an element of
arrayRandomLetter
a value fromarrayRandom
. As you never initializearrayRandom
, 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:
您正在尝试在分配 arrayRandomLetter 之前打印它。
You are trying to print
arrayRandomLetter
before it is assigned.我不会给你答案,但我会给你一个提示:
@fastcodejava 的答案解释了为什么你会看到“盒子”——渲染 ASCII NUL 字符。
@Mark Peters 也是正确的,但这不是最简单的解决方案。
I'm not going to give you the answer, but I will give you a hint:
@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.