本文介绍了If 语句使用 == 给出了意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
        }
    }
}

我有一个名为words"的列表,它包含字符串.此处 Log.i 适用于word"标签很好,但step"语句不执行.似乎 If 条件不起作用.尽管单词"列表包含类似的字符串,但这种方法永远不会进入它.会有什么问题.请帮忙..

I have a List called "words" and it contains strings. Here the Log.i works for the "word" tag fine but the "step" Statement does not executes. Seems the If condition does not work well. like this method never goes into it although the "words" list contains similar strings. What would be the problem. pleas help..

推荐答案

你需要使用String.equals(),而不是==.== 检查两个 Object 引用是否指向同一个 Object:

You need to use String.equals(), not ==. == checks if two Object references refer to the same Object:

if("s".equals(word) || "t".equals(word) || ...

来自 Java 语言规范 3.015.21.3 Reference Equality Operators == and != 部分:

虽然 == 可用于比较 String 类型的引用,但这样的相等测试确定两个操作数是否引用同一个字符串目的.如果操作数是不同的 String 对象,则结果为 false,即使它们包含相同的字符序列.两个字符串 s 和 t 的内容可以通过方法调用 s.equals(t) 来测试是否相等.

这篇关于If 语句使用 == 给出了意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 02:27
查看更多