Counting the number of a certain letter appears in

2020-05-03 10:36发布

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?

4条回答
相关推荐>>
2楼-- · 2020-05-03 10:53

note.substring(i, i) will always return an empty string, so letterTemp.equalsIgnoreCase(letter) will always return false. You should use note.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 same

查看更多
地球回转人心会变
3楼-- · 2020-05-03 10:54

How about:

int countOfLetter = note.length() - (note.replace(letter,"")).length();
查看更多
劳资没心,怎么记你
4楼-- · 2020-05-03 11:03

Your second for-loop seems incorrect.

for (int i = 0; i < notes.size(); i++) {
    String note = (notes.get(i));
    for (int j = 0; i < note.length(); i++) {

Watch out for those index variables i and j.

查看更多
够拽才男人
5楼-- · 2020-05-03 11:05

Instead of passing a String to a method and doing a substring, you can always access and compare the characters, e.g.:

public int countNumberOf(char letter) {
...
String letterTemp = note.charAt(i);
if (letter == letterTemp) {
        count++;
}

Another example:

public static int countOccurrences(String text, char character) {
    int count = 0;
    for (int i = 0; i < text.length(); i++) {
        if (text.charAt(i) == character) {
            count++;
        }
    }
    return count;
}
查看更多
登录 后发表回答