【问题标题】:Unusual android logic operator not working comparing two strings不寻常的android逻辑运算符无法比较两个字符串
【发布时间】:2012-09-13 18:37:24
【问题描述】:

我正在尝试一个简单的检查。如果字符串名称语言环境具有“es”作为值。

public String locale = 
    Locale.getDefault().getLanguage().toLowerCase().toString();

// ...

Log.v(tag, "Idioma del sistema: «" + locale +"»");
if (locale != "es") {
    showDialog(R.string.warningTitleDialog, 
        "We are sorry that this tool is only available in Spanish " +
        "language. See Author menu item for more information. [" + 
        locale + "]");
    locale = "en";
}

adb logcat 将“es”显示为字符串“locale”的内容,但条件内的代码正在执行。

【问题讨论】:

    标签: android string compare logic operator-keyword


    【解决方案1】:

    似乎问题不在于 android 或 JAVA 中的逻辑。 试试这个,告诉我们发生了什么

    if(!locale.equals("en"))
    {
       //Your Code
    }
    

    【讨论】:

    • == 和 != 运算符比较地址
    • 是的,这就是为什么他总是假的。
    【解决方案2】:

    切勿将 != 或 == 与字符串相关联。试试这样的方法:

    if(locale.equals("es"))
    

    如果字符串 locale 和 "es" 包含相同的字符,这将返回 true 顺序。因为equals()方法比较的是String对象中的字符。 == 运算符比较两个对象引用以查看它们是否引用同一个实例。

    更多信息请参见What is the difference between == vs equals() in Java?

    【讨论】:

      猜你喜欢
      • 2018-05-18
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多