开发者

Why is my counter incrementing in loop, but returns zero?

With my current project, I have to keep a counter of the number of insertions into a TreeMap<String, TreeSet<Song>>. The project is to run search of individual words in a string, in this case, song lyrics. I have three tests to determine the course of the map insertions, and my algorithm goes:

  • test if word has more than one character and is not a common word
  • if map already contains the word as a key, test if set already contains the song
  • if true, increment insertion counter
  • if map doesn't contain word as key
    • make new node, add song to set
    • increment counter

I declare the counter as private double insertions; as a class variable.

It is initialized in the constructor:

public SearchByLyricsWords(SongCollection sc) {
    this.songs= sc.getAllSongs();
    buildSongMap(开发者_高级运维);
    insertions=0;
    totalReferences=0;
    averageReferences=0;
}  

The buildMap method:

for (String word:currentLyrics) {
    if (word.length()>1 && !commonWords.contains(word)) {
        if (lyricWords.containsKey(word)) {
            if (!lyricWords.get(word).contains(song))
                insertions++; //this is a non-duplicate song in the set
            lyricWords.get(word).add(song);

        } else {
            TreeSet<Song> songSet= new TreeSet<Song>();
            songSet.add(song);
            lyricWords.put(word, songSet);
            keyWords.add(word);
            insertions++;
        }
        //System.out.println(word+" added");
    }
} //end loop through string

Why is a class variable that is modified in a method, not then giving the correct value in another method?


Try

public SearchByLyricsWords(SongCollection sc) {
    this.songs= sc.getAllSongs();
    insertions=0;
    totalReferences=0;
    averageReferences=0;
    buildSongMap();
}  


It looks like you are setting the variable to zero right after calling the buildsongmap function.


As has already been mentioned, it's a matter of initialization in the constructor. One other thing: in your buildSongMap method, you are adding the song to the map regardless of whether or not it already contains it. Although you're using a Set, which will prevent duplicates, I think it's more readable to only perform the add in the case where it already does not exist.

if (!lyricWords.get(word).contains(song)) {
  insertions++;
  lyricWords.get(word).add(song);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜