【问题标题】:ArrayList content check over entire arrayArrayList 内容检查整个数组
【发布时间】:2013-11-03 10:32:13
【问题描述】:

我试图让它根据包含特定输入字符串的数组条目返回一定数量的数组条目。

/**
* This method returns a list of all words from
* the dictionary that include the given substring.
*/
public ArrayList<String> wordsContaining(String text)
{
    ArrayList<String> contentCheck = new ArrayList<String>();
    for(int index = 0; index < words.size(); index++)
    {
        if(words.contains(text))
        {
            contentCheck.add(words.get(index));
        }
    }
    return contentCheck;
}

我不明白为什么这会不断返回数组中的每个值,而不仅仅是包含字符串位的条目。 谢谢!

【问题讨论】:

    标签: java arrays for-loop return


    【解决方案1】:

    你的情况:

    if(words.contains(text))
    

    检查text 是否在列表中。这将是true 对于所有或没有元素

    你想要的是:

    if(words.get(index).contains(text))
    

    除此之外,如果你使用增强的for语句会更好:

    for (String word: words) {
        if(word.contains(text)) {
            contentCheck.add(word);
        }
    }
    

    【讨论】:

    • @sᴜʀᴇsʜᴀᴛᴛᴀ contains()。 OP 想要检查子字符串。
    • 我的目光转向listcontains :(
    【解决方案2】:

    您的代码中有 2 个问题

    第一个是你检查你的条件

    if(words.contains(text)) - 检查text 是否在列表中

    您可能想要检查给定的列表项是否包含text

    public List<String> wordsContaining(String text)
    {
        List<String> contentCheck = new ArrayList<String>();
        for(String word : words) //For each word in words
        {
            if(word.contains(text)) // Check that word contains text
            {
                contentCheck.add(word);
            }
        }
        return contentCheck;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2019-07-04
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多