【问题标题】:Android - Concatenated Strings aren't detected by if condition [duplicate]Android - 如果条件未检测到连接字符串[重复]
【发布时间】:2015-02-25 08:35:13
【问题描述】:

可能被问到这会很愚蠢,但我找不到让它工作的方法,甚至在互联网上找到解决方案。

我需要连接 2 个字符串(变量 STR_Prefix 和字符串“TA+”)来创建一个新字符串(“ATA+”或“BTA+”),然后我必须检查 if 语句中的值,但它失败了, if 语句未检测到“ATA+”。

但如果我将“STR_Action”的值直接设置为“ATA+”,它就可以完美运行。

public void Test(boolean ok)
{
    String STR_Action = "";
    if (ok) { STR_Prefix = "A"; }
    else    { STR_Prefix = "B"; }

    /* I have tried some ways to concatenate */
    STR_Action = STR_Prefix + "TA+";    // Not working with the if-statement
    // STR_Action = new StringBuilder(STR_Prefix).append("TA+").toString();    // Not working with the if-statement

    /* But if-statement only works when I set STR_Action directly with = "ATA+" or "BTA+"; */
    // STR_Action = "ATA+";    // This assign is detected by the if-statement

    if (STR_Action == "ATA+")
    {
        Toast.makeText(getApplicationContext(), "ATA+", 0).show();
    }
    else if (STR_Action == "BTA+")
    {
        Toast.makeText(getApplicationContext(), "ATA-", 0).show();
    }
    else
    {
        Toast.makeText(getApplicationContext(), "Code not found", 0).show();
    }
}

请帮忙:'(

提前致谢

【问题讨论】:

    标签: android string if-statement string-concatenation


    【解决方案1】:

    尝试这种方式使用.equals()方法进行String比较

     if (STR_Action.equals("ATA+"))
    

    【讨论】:

    • 感谢 M D,它完美运行。但我还是不明白有什么区别:STR_Action = STR_Prefix + "TA+"; STR_Action = "ATA+";两者都意味着 STR_Action = "ATA+" 但 "if" 在使用 "==" 时对两者的工作方式不同: - 连接:失败 - 直接分配:有效
    猜你喜欢
    • 2016-08-09
    • 2013-09-14
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多