【问题标题】:why is this part of my code not following the loop? [duplicate]为什么我的这部分代码不遵循循环? [复制]
【发布时间】:2015-01-21 03:47:44
【问题描述】:

我正在开发一个应用程序,它接收用户的输入并将其添加到 android 中的列表视图中。

我决定制作一个控件来防止用户将空字符串添加到列表中,因为它会使屏幕无用地混乱。我为此编写了这段代码。

    public void addClaims(View v){
    ClaimListController ct = new ClaimListController();
    EditText textView = (EditText) findViewById(R.id.add_claim_field);
    String added = textView.getText().toString();

    if (added != ""){
        final String t = format("added",added);
        ct.addClaim(new Claim(added));
        Toast.makeText(this, t, Toast.LENGTH_SHORT).show();
        textView.setText("");
        //Intent intent = new Intent(MainActivity.this, AddClaim.class);
        //startActivity(intent);
    }else{
        Toast.makeText(AddClaim.this,"Please type something before adding", Toast.LENGTH_SHORT).show();
    }
}
private String format(String string, String added) {
    String formats = string +" "+ added; 
    return formats;
}

但是,if(){} 循环永远不会被检查。我尝试将空字符串更改为“test”并在应用程序中添加测试,它仍然有效。是什么导致代码不检查 IFELSE 条件?

我不是在问如何比较字符串。我在问为什么会出现这个问题。我没有想到这是一个字符串比较问题。

【问题讨论】:

  • 你也可以检查它的长度,即 textView.getText().length > 0

标签: java android if-statement string


【解决方案1】:

您使用的if 条件不会返回true。改用这个:

if (!TextUtils.isEmpty(added))

【讨论】:

    【解决方案2】:

    当您对任何类型的对象使用 != 运算符时,您会比较引用,并且由于您在 if 语句中创建了一个新实例,因此引用总是不同的。

    你可以改用这个 if(added.equals(""))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-13
      • 2013-04-25
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 2012-09-18
      相关资源
      最近更新 更多