public static void countLetters (String s, char x){
int length = s.length();
int count = 0;
int index = 0;
int z = 0;
while (index < length) {
int y = s.indexOf(x, z);
z = z+1;
if(s.charAt(y)==x){
count = count + 1;
}
index = index + 1;
}
System.out.println(count);
Hello everyone, I am a newbie with java so any little guidance would be greatly appreciated. I am trying to write a method to count letter occurrence in a given string and a char.
The current method does count but not quite there. I am asked to use indexOf method to solve this problem. Problem i am having is if I put a text "amazing" and asked to find char 'a' it goes through first 'a' and count updates but then when it comes to char 'm' count again updates which I don't want it.
I am using a book called think java by Allen Downey - Exercise 8.3. Its not any homework :).