简体   繁体   English

需要Java Recursion帮助

[英]Java Recursion help needed

I've been asked to create a public method that does nothing but to call another method that is recursive. 我被要求创建一个公共方法,除了调用另一个递归方法之外什么都不做。 The purpose of the second method is to search for a Int value inside an array. 第二种方法的目的是在数组中搜索Int值。

So far I have this: 到目前为止我有这个:

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++);   
        }
    }
}

However, no matter what number I use, either one in the array or not, it always prints the value of y . 但是,无论我使用什么数字,无论是否在数组中,它总是打印y的值。 I'm still new to recursion and not quite grasping the essence of it yet. 我仍然是递归的新手,并没有完全掌握它的本质。 That's probably why my method isn't working (besides that it is wrong). 这可能是我的方法不起作用的原因(除此之外是错误的)。 Any thoughts? 有什么想法吗? And probably, help to grasp the term better. 并且可能有助于更好地掌握这个术语。

As far you code, this will print y when it finds y in the array because of 就你的代码而言,当它在array找到y时会打印y ,因为

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

And after first call of searchR(x) it is searching the value of cont instead of value of x . 在第一次调用searchR(x)它正在搜索cont的值而不是x的值。 Change searchR(cont++) to searchR(cont++)更改为

cont++; 
searchR(y);

If you want the position of the number you're searching use System.out.println(cont) instead of System.out.println(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);

        }
    }
}
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);
}

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

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