JAVA: saving input to an array

I need to write a program in which the program will generate a random letter, and I will need to store this random character in 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 something wrong with my code? because when I run this and print the array, I get the fields for all the values ​​in the array, and there is a letter that this line of code cannot print

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

thank

+3
source share
3 answers

You assign an element to a arrayRandomLettervalue from arrayRandom. Since you never initialize arrayRandom, its values ​​are 0. 0 is not the value of the printed character, so the fields.

An easy way to select a random character is as follows:

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

arrayRandomLetter .

+1

, :

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

The @fastcodejava answer explains why you see “boxes” - rendering an ASCII NUL character.

@Mark Peters is also true, but this is not the easiest solution.

0
source

Source: https://habr.com/ru/post/1749873/


All Articles