简体   繁体   English

在Java中递归查找数组的长度

[英]Finding the length of an array recursively in Java

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.我尝试传入一个长度为 4 的数组,但该方法只返回 1。我还尝试在 if 语句之外调用递归方法,这只会给出 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您没有使用递归调用的结果,也可以将增量替换为递归调用中的+1 ,并且ilength执行相同的操作,只保留一个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM