[英]Why is my counter incrementing in loop, but returns zero?
在當前項目中,我必須保留對TreeMap<String, TreeSet<Song>>
的插入次數的計數器。 該項目將對字符串中的單個單詞(在這種情況下為歌詞)進行搜索。 我有三個測試來確定映射插入的過程,而我的算法是:
我將計數器聲明為private double insertions;
作為類變量。
它在構造函數中初始化:
public SearchByLyricsWords(SongCollection sc) {
this.songs= sc.getAllSongs();
buildSongMap();
insertions=0;
totalReferences=0;
averageReferences=0;
}
buildMap方法:
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
為什么在一個方法中修改了一個類變量,卻又沒有在另一個方法中給出正確的值呢?
看起來您在調用buildsongmap函數后立即將變量設置為零。
嘗試
public SearchByLyricsWords(SongCollection sc) {
this.songs= sc.getAllSongs();
insertions=0;
totalReferences=0;
averageReferences=0;
buildSongMap();
}
如前所述,這是構造函數中的初始化問題。 另一件事:在buildSongMap方法中,您將歌曲添加到地圖中,而不管它是否已經包含它。 盡管您正在使用Set來防止重復,但我認為僅在不存在添加的情況下執行添加才更容易理解。
if (!lyricWords.get(word).contains(song)) {
insertions++;
lyricWords.get(word).add(song);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.