示例:
// some class method
rock throw_rock() {
// look at its own collection of rocks
// get a rock and do a test on it
rock to_throw = this.rocks[53]; // lets assume its in a map at key 53...
if (to_throw.been_thrown == 1) {
// ok, dont throw this one, instead recurse and find another
this.throw_rock();
} else {
return to_throw;
}
}
在其他课程或主要课程中:
rock g = rock_thower.throw_rock();
// if rock thrower has had to recurse
// g will be null...
我对飞镖很新,不知道为什么会这样。有任何想法吗?这是理智的吗?
如果没有:我做错了什么?
答案 0 :(得分:4)
需要return this.throw_rock()
。
也就是说,您想要返回to_throw
变量或递归调用的结果。
答案 1 :(得分:0)
您使用递归的原因是什么?看起来像do / while可能会起作用:
// some class method
rock throw_rock() {
rock to_throw;
do {
// look at its own collection of rocks
// get a rock and do a test on it
to_throw = this.rocks[53]; // lets assume its in a map at key 53...
} while (to_throw.been_thrown != 1);
return to_throw;
}
与递归方法一样,当所有岩石都不能被抛出时,你需要一个退出条件来处理这个案例。