[英]Recursive Java Method
I have this small block of code used to find the sum of certain numbers: 我有这小段代码,用于查找某些数字的总和:
public class TestClass {
public static int sumOfNums(int num[], int int) {
if(int == num.length-1) return int;
else if( (num[int]%2==0) || num[int] <= 0 ) {
return num[int] + sumOfNums(num, int+1); }
else return 0 + sumOfNums(num, int+1);
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumOfNums(arr, 0));
}
}
However, whenever I run the print statement I get the exception: 但是,每当我运行print语句时,都会出现异常:
Exception in thread "main" java.lang.StackOverflowError
at TestClass.sumOfNums(TestClass.java:13)
at TestClass.sumOfNums(TestClass.java:10)
Can anybody help me? 有谁能够帮助我?
As another user said, your recursion is never ending. 正如另一位用户所说,您的递归永远不会结束。
Changing arr[head-1]
to head-1
should fix this problem on this line: 将arr[head-1]
更改为head-1
可以解决以下问题:
else return 0 + sumNegEven(arr, arr[head-1]);
and changing it here as well: 并在此处进行更改:
return arr[head] + sumNegEven(arr, arr[head-1]); }
public class TestClass {
public static int sumNegEven(int arr[], int head) {
if(head == 0) {
return 0;
} else if( arr[head]%2==0 || arr[head] <= 0 ) {
return arr[head] + sumNegEven(arr, head-1);
} else {
return 0 + sumNegEven(arr, head-1);
}
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumNegEven(arr, arr.length-1));
}
}
By call calling the arr[head-1] you were calling value of the index not index and they last long because recursion is not terminated. 通过调用arr [head-1],您正在调用索引而不是索引的值,并且它们持续很长时间,因为递归没有终止。 If you calling head-1, you are calling actual index and will get answer 21 without exception. 如果您呼叫head-1,则您正在呼叫实际索引,并且将毫无例外地得到答案21。
this won't process the first item in the array 这不会处理数组中的第一项
if(head == 0) { return 0; }
you will have to change it to 您将不得不将其更改为
if(head < 0) { return 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.