【问题标题】:string.contains is always returning truestring.contains 总是返回 true
【发布时间】:2013-06-12 21:50:54
【问题描述】:

我做了一个程序,它接受一个文本文件,将行作为字符串存储在一个数组中。现在我想“过滤”数组的那些条目。

我正在使用 string.contains 来查看每个数组条目是否具有子字符串“05/Aug”。

由于某种原因,它总是返回 true,而实际上它不应该。

这是文件:http://www.santarosa.edu/~lmeade/weblog.txt

这是我的代码:

for (int i=0; i<10;i++)
    {
        boolean check = storestrings[i].contains("05/Aug");
        if(check = true){
            teststring[i] = storestrings[i];
            //System.out.print(storestrings[i]);
        }
        else{
            teststring[i] = null;

            }

    }

【问题讨论】:

    标签: string boolean contains


    【解决方案1】:

    您在 if 语句中使用了赋值运算符而不是相等。应该是这样的:

    if(check == true){
        teststring[i] = storestrings[i];
        //System.out.print(storestrings[i]);
    }
    

    或者干脆

    if (check) {
        teststring[i] = storestrings[i];
        //System.out.print(storestrings[i]);
    }
    

    在您的代码中,当 if 语句中达到 check = true 时,它​​会将 true 分配给 check 变量并返回 true,因此 if 条件始终评估为 true。

    【讨论】:

      猜你喜欢
      • 2013-08-06
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多