0

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:

Exception in thread "main" java.lang.StackOverflowError
    at TestClass.sumOfNums(TestClass.java:13)
    at TestClass.sumOfNums(TestClass.java:10)

Can anybody help me?

1
  • Stack overflow means you aren't stopping the recursive calls - head must never be reaching 0. A bit of "standard debug" should help you find out why... Commented Sep 30, 2018 at 23:18

3 Answers 3

1

As another user said, your recursion is never ending.

Changing arr[head-1] to head-1 should fix this problem on this line:

else return 0 + sumNegEven(arr, arr[head-1]);

and changing it here as well:

return arr[head] + sumNegEven(arr, arr[head-1]); }
Sign up to request clarification or add additional context in comments.

Comments

0
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. If you calling head-1, you are calling actual index and will get answer 21 without exception.

Comments

0

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.