简体   繁体   English

我的递归出了什么问题?

[英]What's wrong with my Recursion?

I need to use recursion to for a method I'm trying to implement. 我需要使用递归来实现我正在尝试实现的方法。 The problem is recursion here isn't working as I thought it would. 问题是这里的递归不起作用,因为我认为它会。 Here's the code I have and I'll explain further below. 这是我的代码,我将在下面进一步解释。

    public void printer(int level) { 
    System.out.println("A Car " + getId());
    for (int j=0; j< carTypes.size(); j++) {

        carTypes.get(j).printer( Index.get(j)+1);
        if (carTypes.get(j) instanceof Toyota) {
            level = 1;
        }
        else {
            level = 1;
            for (int i = 0; i <= j; i++){
                if (j == Index.size()-1) 
                    break;
                if (Index.get(i) == Index.get(j+1)) {
                    number++;
                }
            }
        }
        System.out.println("Is recursion working right?");

    }//End of for loop
}

The problem I am having is I was hoping that everything after carTypes.get(j).printer( Index.get(j)+1); 我遇到的问题是我希望carTypes.get(j).printer(Index.get(j)+1)之后的所有内容; would be ignored and the method would be looped. 将被忽略,方法将循环。 I know if this happens, I will have to find another to deal with my for loop but for now, I just want the recursion working. 我知道如果发生这种情况,我将不得不寻找另一个来处理我的for循环但是现在,我只是希望递归工作。 I am not entirely sure if the information I have provided is enough so if you need more just ask I'll happily give more info. 我不完全确定我提供的信息是否足够,如果您需要更多信息,我会很乐意提供更多信息。

Thanks 谢谢

Recursion: Calling a method from itself. 递归:从自身调用方法。

Now, carTypes.get(j).printer( Index.get(j)+1); 现在, carTypes.get(j).printer( Index.get(j)+1); this line calls printer method each time but on different object. 此行每次调用打印机方法,但在不同的对象上。

So, in fact you are not calling same printer method, and hence recursion is not happening. 所以,事实上你并没有调用相同的printer方法,因此没有发生递归。

EDIT : 编辑:

I know if this happens, I will have to find another to deal with my for loop but for now, I just want the recursion working. 我知道如果发生这种情况,我将不得不寻找另一个来处理我的for循环但是现在,我只是希望递归工作。

Replace 更换

carTypes.get(j).printer( Index.get(j)+1);

with

printer( Index.get(j)+1);

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

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