Reputation: 196
I need to accept a String and check how many letters of the alphabet appeared on it. However, it seems to only count how many times 'a' appears and concatenate that count to all the letters. I can't find where the error is. Any help will be appreciated. Thanks in advance! Here's my code and output.
package javaPackage;
public class Counter {
public static void main(String[] args) {
String letter="abcdefghijklmnopqrstuvwxyz";
String word="banana";
char letterArray[]=letter.toCharArray();
int length = word.length();
int count = 0;
int index = 0;
for (int i=0;i<26;i++) {
while (index < length) {
if (word.charAt(index) == letterArray[i]) {
count++;
}
index++;
}
System.out.println("Letter " + letterArray[i]+ " appeared "
+ count+ " times");
}
}
}
Output:
Letter a appeared 3 times
Letter b appeared 3 times
Letter c appeared 3 times
Letter d appeared 3 times
Letter e appeared 3 times
Letter f appeared 3 times
Letter g appeared 3 times
Letter h appeared 3 times
Letter i appeared 3 times
Letter j appeared 3 times
Letter k appeared 3 times
Letter l appeared 3 times
Letter m appeared 3 times
Letter n appeared 3 times
Letter o appeared 3 times
Letter p appeared 3 times
Letter q appeared 3 times
Letter r appeared 3 times
Letter s appeared 3 times
Letter t appeared 3 times
Letter u appeared 3 times
Letter v appeared 3 times
Letter w appeared 3 times
Letter x appeared 3 times
Letter y appeared 3 times
Letter z appeared 3 times
Upvotes: 1
Views: 119
Reputation: 393781
You never reset your counter
and index
variables :
for (int i=0;i<26;i++) {
index = 0; // added
counter = 0; // added
while (index < length) {
if (word.charAt(index) == letterArray[i]) {
count++;
}
index++;
}
}
That said, this implementation is very inefficient. You can count all occurrences in a single for loop.
countArray[0]
will count the occurrences of 'a', countArray[1]
will count the 'b's, and so on.
String word="banana";
int countArray[]=new int[26];
for (int i = 0; i < word.length(); i++) {
countArray[word.charAt(i) - 'a']++;
}
for (int i = 0; i < countArray; i++) {
System.out.println("Letter " + (char)('a' + i) + " appeared " + countArray[i] + " times");
}
Upvotes: 4
Reputation: 1123
You have to reset index to 0 once you left the inner loop. Same with count. Otherwise he only runs the inner loop once for the letter A and then never again, because the condition in the while isn't fulfilled.
Edit: efficient solution
int[] letterOccurences = new int[26];
for (int i = 0; i < letterOccurences.length; i++) {
letterOccurences[i] = 0;
}
for (int i = 0; i < word.length(); i++) {
letterOccurences[letter.charAt(i) % 97]++;
// 'a' % 97 will return 0, 'b' % 97 will return 1 and so on.
//Thus, in 0 the count of 'a's, in 1 the count of 'b's and so on will be tracked.
}
Upvotes: 0
Reputation: 2277
You are not resetting index
and count
.So it is showing results obtained for a
only.
Upvotes: 0