Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

don't know how to prevent java.lang.StackOverflowError

I am supposed to write a recursive(!) method to count the amount of occurrences of a given integer in an integer array and return true if even and false if odd. This is my code so far:

public static boolean evenNumberOf(int x, int[] arr) {

    if (arr == null || arr.length == 0)
        return false;
    int count = counting(x, arr, 0, 0);
    if (count % 2 == 0) {
        System.out.print("true");
        return true;
    } else {
        System.out.print("false");
        return false;
    }
}

public static int counting(int x, int[] arr, int index, int count) {

    if (arr[index] == x && index < arr.length) {
        return counting(x, arr, index++, count++);
    } else {
        return counting(x, arr, index++, count);
    }
}

It works for

evenNumberOf(2, new int[] { 1, 2, 3, 2 });

but it gives java.lang.StackOverflowError for

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

evenNumberOf(1, new int[] { 1, 2, 3, 2 });

I am not sure how to prevent this endless recursive loop, as I’m new to programming and it’s my first time using recursion.
Thanks in advance.

>Solution :

Any recursion should have a stop condition and 1 or more recursive calls.

in this example, the stop condition is index >= arr.length so you start writing the function as folows:

public static int counting(int x, int[] arr, int index) {
    if (index >= arr.length) {
        return 0;//there are 0 x's between index and arr.length
    }

after you handled the stop condition, you need to write the rest:

public static int counting(int x, int[] arr, int index) {
    if (index >= arr.length) {
        return 0;//there are 0 x's between index and arr.length
    }
    int countAfterIndex = counting(x, arr, index+1);//the amount of x's starting from index+1
    if (x == arr[index]) {
        return countAfterIndex + 1;//there is 1 more to add
    } else {
        return countAfterIndex; //the amount of x's after index is the same as the amount from index.
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading