1

I try save alphabet A-Z to my array, but I don't understand, why I get only this output: Z.

public class Main {

    public static void main(String[] args) {

        char []tab = new char[25];

        for (int i = 0; i<25; i++) {
            for (int j=65; j<91; j++) {
                tab[i] = (char)j;
            }
        }

        for (int i=0; i<25; i++) {
            System.out.println(tab[i]);
        }

    }
}
  • 2
    That's because of the inner loop which will set every element of `tab` to `(char)90`. Try `tab[i] = 65 + i;` instead. – Thomas Dec 11 '18 at 17:21

3 Answers3

1

You don't need nested loop, try this:

char[] tab = new char[26];
for (int i = 0, j = 65; j < 91; j++, i++) {
  tab[i] = (char) j;
}

for (int i = 0; i < 26; i++) {
  System.out.println(tab[i]);
}

Also, array size should be 26 not 25.

Aditya Narayan Dixit
  • 2,105
  • 11
  • 23
1

Your algorithm is wrong.

Check this simpler solution:

public static void main(String[] args)
{
   char []tab = new char[25];

   for (int i = 0; i<25; i++) {
            tab[i] = (char)(i+65);
    }

    for (int i=0; i<25; i++) {
        System.out.println(tab[i]);
    }
}

Your code puts all the letters from A to Z in each slot of the tab array, when executing the 'j' loop, that's why you have only Zs.

David Raluy
  • 184
  • 5
1

Lets see how your code works:

for (int i = 0; i<25; i++) {       //1
    for (int j=65; j<91; j++) {    //2
        tab[i] = (char)j;          //3
    }                              //4
}                                  //5

1) Outer loop sets i=0,
2) Inner loop sets j=65
3) (char)65 represents 'A' ant is placed in tab[0]
2) Inner loop sets j=66
3) (char)66 represents 'B' and is also placed in tab[0]

Here you should notice the problem, which is that inner loop is working on same i, so while iterating over A...Z it is modifying same array location, which means that location will hold last value placed there, which is 'Z'. (BTW i<25 should be i<26)

Possible solution

don't use inner loop, you can calculate value which should be placed at index by adding i to 65 which in Unicode Table is codepoint of 'A'

for (int i=0; i<26; i++)
    tab[i] = (char)(65+i);

BTW you can farther improve readability of this code by avoiding magic numbers (more info: What is a magic number, and why is it bad?). So this code can be rewritten into something like:

int amountOfLetters = 'Z' - 'A' + 1;
char[] tab = new char[amountOfLetters];

int i = 0;
for (char ch = 'A'; ch <= 'Z'; ch++) {
    tab[i++] = ch;
}

System.out.println(new String(tab));
Pshemo
  • 122,468
  • 25
  • 185
  • 269