我有一段我不使用的代码,但这会影响我的输出。
public class Recursion {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<>();
list.add(2);
list.add(4);
list.add(6);
list.add(8);
// ArrayList<Integer> copy = new ArrayList<>();
// list.add(2);
// list.add(4);
// list.add(6);
// list.add(8);
System.out.println(sum(list));
}
public static int sum(ArrayList<Integer> array) throws Exception {
if (array.size() == 1)
return array.get(0);
else {
int x = array.get(0);
array.remove(0);
return x + sum(array);
}
}
}
给20岁
没有对“复制”的评论,它给出40,但我不使用它。
答案 0 :(得分:1)
您在注释的代码块上调用list.add
,而不是copy.add
。