我的数组列表的 Java contains() 无法循环工作

标签 java arraylist contains

我有一个数组列表,我想检查数组列表是否有某个字符串。我发现 .contains() 可以解决这个问题。但是当我循环运行它来检查数组列表中的单词“bot”时。结果还包括“聊天机器人”和“机器人”作为“机器人”,这不应该是我想要的结果。但如果我在没有循环的情况下执行此操作,它就可以正常工作,但我不明白为什么。

代码:

// Java code to demonstrate the working of 
// contains() method in ArrayList of string 

// for ArrayList functions 
import java.util.ArrayList; 

public class test { 
    public static void main(String[] args) 
    { 

        // creating an Empty String ArrayList 
        ArrayList<String> arr = new ArrayList<String>(4); 
        ArrayList<String> arr2 = new ArrayList<String>(4);

        // using add() to initialize values 
        arr.add("chatbot"); 
        arr.add("robot"); 
        arr.add("bot"); 
        arr.add("lala"); 

        // use contains() to check if the element 
        for (int i=0;i<arr.size();i++){
            boolean ans = arr.get(i).contains("bot"); 
            if (ans) {System.out.println("1: The list contains bot"); }
            else
                {System.out.println("1: The list does not contains bot");}
        }

        System.out.println();

        for (String str : arr) {
        if (str.toLowerCase().contains("bot")) {
            System.out.println("2: The list contains bot");;
        }
        else
            {System.out.println("2: The list does not contains bot");}
        }


        // use contains() to check if the element 
        System.out.println();
        arr2.add("robot");
        boolean ans = arr2.contains("bot"); 

        if (ans) 
            System.out.println("3: The list contains bot"); 
        else
            System.out.println("3: The list does not contains bot"); 
    } 
} 

结果:

1: The list contains bot
1: The list contains bot
1: The list contains bot
1: The list does not contains bot

2: The list contains bot
2: The list contains bot
2: The list contains bot
2: The list does not contains bot

3: The list does not contains bot

最佳答案

您基本上是在检查 arraylist arr2 是否包含单词“bot”,但事实并非如此。您必须检查第一个元素是否包含该单词。 arr2[0].contains("bot")

关于我的数组列表的 Java contains() 无法循环工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60047165/

相关文章:

java - 无法使用无服务器本地调用 AWS Lambda

c# - 将代码从 Java 转换为 C#/ASP.NET

JAVA如何创建一维和多维数组

java - 在Android中创建JSON ArrayList/JSON对象并发送到PHP

c - 我的 contains 函数有什么问题?

python - 在任何列中搜索关键字的数据框并获取行

java - 从 HTML 页面和 java 应用程序调用 Web 服务

java - 区分父类的数组列表中的每个子类

java - 检查来自 URL : Is it a file or webpage? 的内容

java - URLConnection 有时返回空字符串响应?