I'm trying to make a method that returns the length of an array recursively (as a learning exercise). I tried passing in an array of length 4, but the method just returns 1. I also tried calling the recursive method outside of the if statement and that just gives a StackOverflowError. Why is this method returning one and how can I get it to return the correct length?
public static int findArrayLength(int i, int length, int[] array) {
if(i < array.length) {
length += 1;
i++;
findArrayLength(i, length, array);
}
return length;
}
You're not using the result of the recursive call, also you can replace the increment, to a +1
inside the recursive call, and i
and length
are doing same, keep one only
public static int findArrayLength(int i, int[] array) {
if (i < array.length) {
return findArrayLength(i + 1, array);
}
return i;
}
System.out.println(findArrayLength(0, new int[]{1, 1, 1})); // 3
System.out.println(findArrayLength(0, new int[]{1, 1, 1, 1})); // 4
System.out.println(findArrayLength(0, new int[]{1, 1, 1, 1, 1})); // 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.