當你比較字符串,你需要使用.equals()
方法,而不是==
操作。因此,您需要將if (word == stopwords[i])
更改爲if(word.equals(stopwords[i]))
。
加長版:
粗略地講,在==
運營商確定兩個變量指向同一對象(在我們的例子:是否word
,並在同一字符串對象stopwords[i]
點)。 .equals()
方法確定兩個對象是否相同(內容明智)。如果你的情況下程序無法產生所需的輸出,因爲你有兩個不同的字符串持有相同的內容。因此,通過==
比較它們產生false
,而通過.equals()
比較它們會產生「真實」。
編輯
看了張貼在鏈接的程序,我發現了幾件事情:首先,內部的循環的條件,就必須改變以i < stopwords.length
。其次,newWordList
對象未正確初始化。這是新的LinkedList<String>(Arrays.asList(parts))
這意味着LinkedList
將包含一個值爲the and of the
的String元素,這不是您想要的。您想要的LinkedList
包含字符串元素如下:
- 元素0:
the
- 元件1:
and
- 元件2:
of
- 元件3:
the
因此初始化需要更改爲new LinkedList<String>( Arrays.asList(parts.split(" ")))
。具體而言,parts.split(" ")
將給定的字符串(split
)拆分爲單獨的單詞,返回這些單詞的數組。
public static void main (String[] args) throws java.lang.Exception
{
String[] stopwords = { "the", "and" };
String parts = "the and of the";
LinkedList<String> newWordList = new LinkedList<String>(
Arrays.asList(parts.split(" ")));
for (Iterator<String> iter = newWordList.iterator(); iter.hasNext();) {
String word = iter.next();
for (int i = 0; i < stopwords.length; i++) {
if (word.equals(stopwords[i])) {
iter.remove();
}
}
}
System.out.println(newWordList.toString());
}
,如果你想,如果你想刪除重複使用'Set' **'iterate' **和刪除使用'Iterator'但首先決定你的操作 – emotionlessbananas
@FlyingZombie感謝您的評論。我想保留重複的內容,這就是爲什麼我不使用'Set'。 –
雖然最初這個問題似乎是關於字符串比較,但在更仔細的檢查中,它也是關於字符串分割/集合初始化。 –