简体   繁体   中英

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

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.

Replace

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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