private void refineWords() {
for(String word : words){
Log.i("word", word);
if (word == "s" || word == "t" || word == "am" || word == "is" || word == "are" || word == "was" || word == "were" || word == "has" ||
word == "have" || word == "been" || word == "will" || word == "be" || word == "would" || word == "should" || word == "shall" ||
word == "must" || word == "can" || word == "could" || word == "the" || word == "as" || word == "it" || word == "they" ||
word == "their" || word == "he" || word == "she" || word == "his" || word == "her" || word == "him" || word == "its" ||
word == "in" || word == "on" || word == "a" || word == "at") {
Log.i("step", "step Success!!");
words.remove(word);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个名为"单词"的列表,它包含字符串.这里Log.i适用于"word"标签,但"step"语句不会执行.似乎If条件不能正常工作.虽然"单词"列表包含类似的字符串,但是这种方法永远不会进入它.会有什么问题.请求帮助..
hmj*_*mjd 19
你需要使用String.equals(),而不是==.==检查两个Object引用是否引用相同Object:
if("s".equals(word) || "t".equals(word) || ...
Run Code Online (Sandbox Code Playgroud)
从部分15.21.3引用相等运算符==和=!在的Java语言规范3.0:
虽然==可用于比较String类型的引用,但这样的相等性测试确定两个操作数是否引用相同的String对象.如果操作数是不同的String对象,则结果为false,即使它们包含相同的字符序列.可以通过方法调用s.equals(t)测试两个字符串s和t的内容是否相等.
正如其他人所说,你object.equals(otherObject)用来比较Java中的对象.
但你的方法是完全错误的.
试试吧
Set stopWords = new HashSet(Arrays.asList("s", "t", "am",
"is", "are", "was", "were",
"has", "have", "been",
"will", "be", ...));
Run Code Online (Sandbox Code Playgroud)
然后
private void refineWords() {
words.removeAll(stopWords);
}
Run Code Online (Sandbox Code Playgroud)
你应该完成.
此外,请注意,使用当前代码,您将得到一个,ConcurrentModificationException因为您在迭代时尝试更改集合.
因此,如果您不能使用上述内容words.removeAll(stopWords),那么您必须使用更详细的Iterator.remove()方法:
private void refineWords() {
for (Iterator<String> wordsIterator = words.iterator(); wordsIterator.hasNext(); ) {
String word = wordsIterator.next();
if (stopWords.contains(word)) {
wordsIterator.remove();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
708 次 |
| 最近记录: |