I'm trying to make a program that counts all instances of a letter in a user-inputted phrase. For example, the phrase "Hello" will output "h: 1", "e: 1", "l: 2", "o: 1".
I've figured out how to find and count all the letters, except "a". When I compare "a" to itself more than once, it returns a different value each time (so the phrase "aaaa" would give me a: 1, b: 1, c: 1, d: 1)
Here's the code I'm using:
int[] countLetter = new int[26];
char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
phrase = phrase.toLowerCase();
String a = "a";
for (int i = 0; i<phrase.length(); i++ ) {
char count = phrase.charAt(i);
if (Character.isLetter(count))
countLetter[a.compareTo(phrase.substring(i))*-1] = countLetter[a.compareTo(phrase.substring(i))*-1] + 1;
}
for (int i = 0; i<26; i++) {
if (countLetter[i]>0) {
System.out.println(alphabet[i] + ": " + countLetter[i]);
}
}
I'm not sure what I'm doing wrong, so how can I get "a" to stay the same?