【问题标题】:How to manipulate array lists - Computer Science homework如何操作数组列表 - 计算机科学作业
【发布时间】:2015-01-07 02:03:34
【问题描述】:

在计算机科学领域,我们目前正在研究 ArrayList 并对其进行操作。我在家庭作业的一个问题上遇到了一些麻烦。

你实际上可以在这个网站here上做和查看作业:

我想知道为什么我的代码(见下文)不正确。

问题是:一个数组列表包含一个动物列表。如果动物是猫(即动物的描述包含单词“cat”或“Cat”),则将其添加到新的数组列表中。返回新的猫数组列表。

但是我会告诉你我卡在哪里了。这就是我到目前为止所拥有的(同样,可以使用上面的链接找到关于问题的一小部分信息。

public String[] catty(String[] animals) { 

    ArrayList<String> animalsList = new ArrayList<String>();
    for (int i=0; i<animals.length; i++)
    {
       animalsList.add(animals[i]);
    }

    ArrayList<String> catsList = cattyB(animalsList);

    String cats[] = new String[catsList.size()];
    for (int i=0; i<catsList.size(); i++)
    {
       cats[i]=catsList.get(i);
    }

    return cats;
}

public ArrayList<String> cattyB(ArrayList<String> animalsList) 
{
  for (int i=0; i<animalsList.size(); i++)
  {
    if (animalsList.get(i).indexOf("Cat")>-1 || animalsList.get(i).indexOf("cat")>-1)
    {
      animalsList.add(animalsList.get(i));
    }
    return animalsList;
  }
  return animalsList;


}

【问题讨论】:

  • 有什么问题?
  • @August 我想知道为什么我的代码不正确。抱歉问题不清楚。它已被编辑。
  • 另外,请确保你在 cattyB 的末尾有一个 return 语句,因为你目前只有一个 for 循环。
  • @matthewrball 您可能想告诉我们 a:预期输出是什么,b:实际输出是什么。只是“它不起作用”不是很有帮助。请注意,codingbat 网站甚至会为您提供这些信息...
  • 你能用伪代码或简单的英语向我解释 cattyB 方法的作用吗?如果你能做到,那么我也许可以帮你找出错误。

标签: java arraylist computer-science


【解决方案1】:

您正在将您的猫添加到传递给函数的原始列表中。这是错误的。您应该创建一个新的,将猫添加到其中并返回它,不是吗?这样做...

【讨论】:

  • 对不起,我是个初学者。你能帮我解决这个问题吗?
  • 这个。提示:在 cattyB 函数中,使用新的 ArrayList 而不是在旧列表中添加更多。这样只有 Cats/cats 被添加到其中。
  • 我需要创建一个新的 ArrayList 吗?还是我只是提到它@AimanB
  • 只有一种方法可以找出答案 ;-)
  • @matthewrball 是的,他们可以。但他们正试图做一些比这更好的事情。他们试图教你如何解决问题。
【解决方案2】:

所以这里缺少的一点是 cattyB 函数中需要一个新的 ArrayList。然后你可以解析animalsList并将名称从那里放入新的ArrayList。最后,我们需要返回包含猫的新 ArrayList,而不是返回原始的animalsList。这是带有修正的 cattyB 函数。我对 catty 没有做任何更改。在所引用的网站 OP 上确认正确。

public ArrayList<String> cattyB(ArrayList<String> animalsList) 
{
  ArrayList<String> newListWithCats = new ArrayList<String>();
  for (int i=0; i<animalsList.size(); i++)
  {
    if (animalsList.get(i).indexOf("Cat")>-1 || animalsList.get(i).indexOf("cat")>-1)
    {
      newListWithCats.add(animalsList.get(i));
    }
  }
  return newListWithCats;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 2017-07-07
    • 2012-03-28
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多