JAVA: storing input into array
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 wi开发者_开发技巧th 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
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()));
You are trying to print arrayRandomLetter
before it is assigned.
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.
精彩评论