when you compare strings you need to use the .equals()
method and not the ==
operator. Thus, you need to change if (word == stopwords[i])
to if(word.equals(stopwords[i]))
.
Longer version:
Roughly speaking, the ==
operator determines if two variables point at the same object (in our case: whether word
and stopwords[i]
point at the same string object). the .equals()
method determines if two objects are identical (content wise). If your case the program failed to produce the desired output because you had two different strings holding the same content. Thus, comparing them via ==
yields false
whereas comparing them via .equals()
yields `true.
EDIT
Having read the program posted in the link, I found a couple of things: First, the inner for loop's condition had to be changed to i < stopwords.length
. Second, the newWordList
object was not initialized correctly. It was new LinkedList<String>(Arrays.asList(parts))
which means that the LinkedList
will contain a single String element whose value is the and of the
, which is not what you want. You want the LinkedList
to contain four string elements as follows:
- element 0:
the
- element 1:
and
- element 2:
of
- element 3:
the
Thus the initialization need to be changed to new LinkedList<String>(
Arrays.asList(parts.split(" ")))
. Specifically, parts.split(" ")
breaks-down the given string (split
) into separate words returning an array of these words.
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());
}