需要Java Recursion帮助

时间:2016-01-24 21:41:58

标签: java recursion

我被要求创建一个公共方法,除了调用另一个递归方法之外什么都不做。第二种方法的目的是在数组中搜索Int值。

到目前为止,我有这个:

int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};
int cont = 0;

public int searchI(int x) {
    searchR(x);
    return x;
}

private void searchR(int y) {
    if (cont < array.length) {
        if (array[cont] == y) {
            System.out.println(y);
        } else {
            searchR(cont++);   
        }
    }
}

但是,无论我使用什么号码,无论是否在数组中,它总是打印y的值。我还不熟悉递归,还没有完全掌握它的本质。这可能是我的方法不起作用的原因(除此之外是错误的)。有什么想法吗?并且可能有助于更好地掌握这个术语。

2 个答案:

答案 0 :(得分:2)

根据您的代码,当y因{/ 1>}而发现y时会打印array

if (array[cont] == y) {
     System.out.println(y);
}

首次调用searchR(x)后,它会搜索cont的值,而不是x的值。将searchR(cont++)更改为

cont++; 
searchR(y);

如果您希望搜索号码的位置使用System.out.println(cont)而不是System.out.println(y)

int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};
int cont = 0;

public int searchI(int x) {
    searchR(x);
    return x;
}

private void searchR(int y) {
    if (cont < array.length) {
        if (array[cont] == y) {
            System.out.println(y); //System.out.println(cont); if you want the position as output
        } else {
            cont++;
            searchR(y);

        }
    }
}

答案 1 :(得分:2)

static final int [] array={1,6,2,7,3,9,5};
 public static void searchI(int x)
{
    System.out.println(x);
    System.out.println(searchR(x,0));
}

   private static int searchR(int x,int _index)
{
    if(_index>array.length)
        return -1;
    else if(array[_index]==x)
        return _index;
    else
        return searchR(x,++_index);
}