jolt
jolt

Reputation: 53

Iterating Numbers and Alphabet for hashmap

I'm trying to associate each letter of the alphabet with its corresponding number. 0=a, 1=b, 2=c, etc.

Although my numbers are sequencing properly, my letters are all coming out as "z." What am I doing wrong (with my loop)?

public static void cipherMap (Map<Integer, Character> map) {
    for (int i = 0; i <= 25; i++) { 
        for (Character alphabet = 'a'; alphabet <= 'z'; alphabet++) {
            map.put(new Integer(i), alphabet);
        }   
    }
}

output:

0: z
1: z
2: z
3: z
4: z
5: z ... so on

Upvotes: 1

Views: 1168

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201527

The last step of your inner loop sets every i to z. Remove the inner for loop and do something like,

public static void cipherMap (Map<Integer, Character> map) {
    for (int i = 0; i <= 25; i++) { 
        map.put(i, (char) ('a' + i));   
    }
}

Upvotes: 2

Related Questions