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); } } }
我有一个名为“单词”的列表,其中包含字符串。在这里Log.i可以很好地处理“ word”标签,但不会执行“step”语句。似乎如果条件不能很好地工作。尽管“单词”列表包含类似的字符串,但这种方法永远不会进入它。怎么了 请帮助
您需要使用String.equals(),不==。==检查两个Object引用是否引用相同的内容Object:
String.equals()
==
if("s".equals(word) || "t".equals(word) || ...
从部分15.21.3引用相等运算符==和=!在的Java语言规范3.0:
虽然==可以用来比较String类型的引用,但是这种相等性测试确定两个操作数是否引用相同的String对象。如果操作数是不同的String对象,则结果为false,即使它们包含相同的字符序列也是如此。可以通过方法s.equals(t)来测试两个字符串s和t的内容是否相等。