我需要使用递归来实现我想要实现的方法。问题是这里的递归并没有像我想象的那样工作。这是我的代码,我将在下面进一步解释。
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
}
我遇到的问题是我希望 carTypes.get(j).printer( Index.get(j)+1); 之后的所有内容将被忽略并且该方法将被循环。我知道如果发生这种情况,我将不得不找到另一个来处理我的 for 循环,但现在,我只希望递归工作。我不完全确定我提供的信息是否足够,因此如果您需要更多信息,请询问,我很乐意提供更多信息。
谢谢
最佳答案
递归:从自身调用方法。
现在,carTypes.get(j).printer( Index.get(j)+1);
这行代码每次都会调用打印机方法,但在不同的对象上。
所以,实际上您没有调用相同的 printer
方法,因此不会发生递归。
编辑:
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.
替换
carTypes.get(j).printer( Index.get(j)+1);
与
printer( Index.get(j)+1);
关于java - 我的递归有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10377123/