I have an ArrayList that stores notes (strings) in the form of "do the dishes". I have a notes class with a method that is supposed to go through all the notes in the ArrayList and count the number of times a certain letter appears. This is the method I have written so far:
public int countNumberOf(String letter) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String note = (notes.get(i));
for (int j = 0; i < note.length(); i++) {
String letterTemp = note.substring(i, i);
if (letterTemp.equalsIgnoreCase(letter)) {
count++;
}
}
}
return count;
}
However, when I run the program, I'm getting zero for the number of times the letter "a" appears even though I know it's present in the ArrayList. What am I doing wrong?
note.substring(i, i)
will always return an empty string, soletterTemp.equalsIgnoreCase(letter)
will always returnfalse
. You should usenote.substring(i, i+letter.length())
Although I suggest that you use
char
for comparison, in this kind of task. Mostly for simplicity's sake, and to avoid unecessary intermediate strings. The logic would be the sameHow about:
Your second for-loop seems incorrect.
Watch out for those index variables
i
andj
.Instead of passing a
String
to a method and doing asubstring
, you can always access and compare the characters, e.g.:Another example: