【发布时间】:2024-04-15 10:10:02
【问题描述】:
给定一个 arraylist 输入,我必须创建一个递归方法,该方法返回列表中奇数位置的值的总和,从中减去值的位置
例如:
private int method(ArrayList<Integer> list, int k)
{
int s = 0;
s = list.get(k);
if(k == list.size()) return s;
return s + method(k+1);
}
public int method(ArrayList<Integer> list)
{
return method(list,0);
}
(主要)
List<Integer> list = Arrays.asList(2, 5, 3, 7, 11, 1);
ArrayList<Integer> l2 = new ArrayList<>(list);
SumSub test = new SumSub(l2);
System.out.println(test.method(l2));
[2, 5, 3, 7, 11, 1] ---> 2-5+3-7+11-1=3(应该显示的结果) 但结果总是 22,我不明白为什么
【问题讨论】:
-
您的代码不应编译,因为您正在调用
method(k+1),但没有带有单个 int 参数的方法。你确定你已经向我们展示了返回 22 的工作代码吗? -
'从中减去值的位置' - 你的意思是应该减去偶数值,对吧?根据这个解释修正了我的答案。
标签: java list recursion arraylist indexing