Java 通过递归查找数组中数字的第一个索引

Java 通过递归查找数组中数字的第一个索引,java,recursion,Java,Recursion,所以在这个问题中,我试图通过递归找到数组中给定数字的索引,它给出了错误的输出。任何协助都将不胜感激。 这是我的密码: public class first_index { // i refers to index, x is element public static int firstIndex(int input[], int x,int i){ if(i >= input.length - 1){ if(input[i]==x)

所以在这个问题中,我试图通过递归找到数组中给定数字的索引,它给出了错误的输出。任何协助都将不胜感激。 这是我的密码:

public class first_index {
// i refers to index, x is element
    public static int firstIndex(int input[], int x,int i){

        if(i >= input.length - 1){
            if(input[i]==x)
                return i;
            else
                return -1;
        }
        int b;
        b=firstIndex(input,x,i+1);
        if(b!=-1){
            if(input[i]==x)
                return i+1;
            else
                return i-1;
        }
        else{
            if(input[i]==x)
                return i;
            else
                return -1;
        }
        }

    public static void main(String[] args) {
        int input[] = {1,2,3,5,9,0};
        System.out.println(firstIndex(input,9,0));

    }
}
那么:

public static int firstIndex(int input[], int x,int i){
    if(i >= input.length) {
        return -1;
    } else if(input[i]==x)
        return i;
    } else {
        return firstIndex(input,x,i+1);
    }
}

如果当前索引包含要查找的数字,则应返回该索引

只有当它不存在时,才应该进行递归调用以搜索数组其余部分中的数字

public static int firstIndex(int input[], int x,int i) {
    if (i > input.length - 1) { // i is beyond the indices of the array, 
                                // so the number is not found
        return -1;
    }

    if(input[i]==x) { // current index is the first index that contains x
        return i;
    } else { // make a recursive call to find the first index of x in the rest of the array
        return firstIndex(input,x,i+1);
    }
}
也可以写为:

public static int firstIndex(int input[], int x,int i) {
    if(i > input.length - 1) {
        return -1;
    }

    return (input[i] == x) ? i : firstIndex(input, x, i+1);
}