for和else布尔方法中的错误

这是我得到的错误:

    - This method must return a result of type boolean

这是代码:

public boolean seleccionar (Aeronave otra) {
    for (int i=0; i < this.as.length; i++) {
    if (otra !=null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
    return true;
    }
    else {
        return false;
    }
    }
}  }
评论
  • 浅浅小鸣
    浅浅小鸣 回复

    Add a return false before the last brace. Your function doesn't return anything if this.as.length == 0, and Java is giving a compile error because of that.

  • 老鸡抓小鹰
    老鸡抓小鹰 回复

    Your code will exit on first loop element. But when array this.as is empty, so loop will not execute, then your function is missing a return value -therefore compiler does not allow this.

    To solve this issue, simply move return false after the loop ends.

    public boolean seleccionar (Aeronave otra) {
        for (int i=0; i < this.as.length; i++) {
           if (otra !=null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
              return true;
           }
        }
        return false; // if no elements are matching loop condition, return false
     }}
    
  • 珍VC
    珍VC 回复

    问题是for循环可能会遍历所有元素并最终到达末尾,而不会返回任何结果。在这种情况下,我们返回false来确保这一点。

    public boolean seleccionar (Aeronave otra) {
        for (int i=0; i < this.as.length; i++) {
            if (otra !=null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
                return true;
            }
        }
        return false;
    }