0

这似乎是不可能的飞镖?即让一个类方法递归并最终返回一个对象?当我运行递归方法时,如果它至少递归一次,它总是返回 null ......

例子:

// 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...

我对飞镖很陌生,不知道为什么会这样。有任何想法吗?这是理智的吗?

如果不是:我做错了什么?

4

2 回答 2

4

它需要是return this.throw_rock()

也就是说,您想返回to_throw变量或递归调用的结果。

于 2012-08-05T02:26:35.457 回答
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;
}

与递归方法一样,您需要一个退出条件来处理无法投掷所有石头的情况。

于 2012-08-05T02:47:20.300 回答