【发布时间】:2014-12-02 18:55:07
【问题描述】:
我已经完成了家庭作业的第一部分,但我开始陷入困境(对说明部分感到困惑。我目前有一些完整的代码:
import java.util.*;
import java.util.ArrayList;
public class ListMethods
{
public static ArrayList<Integer> makeList(int n)
{
ArrayList<Integer> tempList = new ArrayList<Integer>();
if (n <= 0) // The smallest list we can make
{
return tempList;
}
else // All other size lists are created here
{
}
return tempList;
}
}
public class ListMethodRunner
{
public static void main(String[] args)
{
ArrayList<Integer> tempList = ListMethods.makeList(0);
if(tempList.size() == 0)
{
System.out.println("The list is empty.");
}
else
{
for(Integer i: tempList)
{
System.out.println(i);
}
}
}
}
现在的目标是使用这些指令: 每当一个方法调用自身时,该方法都是递归的。通过调用相同的 再次使用方法,使用较小实例的解决方案来解决问题的每个实例。从逻辑上讲,这 过程必须在某处停止。在我们的 ArrayList 问题的情况下,它在我们调用时停止 制作清单(0)。这是我们在 Lab 1.1 中手动解决的问题。 每当我们调用 makeList(n - 1) 时,我们都会收到一个包含 1、2、3、...、n - 1 的 ArrayList。我们如何使用 生成一个 1, 2, 3, ..., n 的 ArrayList? 将该代码添加到 else 块并完成 makeList 方法。使用测试工具测试您的代码 通过更改传递给 makeList 的参数。你能列出一个包含 100 项的清单吗?
我需要列出一个包含 100 个项目的列表,但我不明白如何使用 (n-1) 列出 100 个项目。如果我理解正确,看到我们不能使用 while 循环,我会使用类似 (int i = 0, i
【问题讨论】:
-
这个问题具体是指使用递归,所以我认为任何类型的循环都是不允许的。
标签: java arrays recursion arraylist