user10438581
user10438581

Reputation:

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:

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

Can anybody help me?

Upvotes: 0

Views: 74

Answers (3)

ynota
ynota

Reputation: 36

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

Upvotes: 0

imsaiful
imsaiful

Reputation: 1614

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.

Upvotes: 0

Josh
Josh

Reputation: 406

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

Upvotes: 1

Related Questions