簡體   English   中英

無法分配給我創建的Java數組

[英]Can't assign to array I've created java

我是Java的初學者,我嘗試使用我創建的數組,但始終無法重新識別它。 有人知道這里可能缺少什么嗎?

更具體地說,命令bookArray.length使此錯誤。

Library(int maxBookCapacity){
    Book bookArray[]= new Book[libraryMaxBookCapacity];
}

boolean inLibrary(Book book){
    for(int i=0; i<bookArray.length; i++ ){
        if (book==bookArray[i]){
            return true;
        }
    }
    return false;
}

bookArray是一個局部變量,在定義方法之外不能訪問spocan。 實際上local就是這樣:名稱bookArray僅在構造函數內部可用。

如果在inLibrary需要它, inLibrary將is聲明為封閉類中的字段:

public class Library {

  private final Book[] bookArray;

  public Library(int maxBookCapacity){
    bookArray = new Book[libraryMaxBookCapacity];
  }

  public boolean inLibrary(Book book){
    for(int i = 0; i < bookArray.length; i++ ){
      if (book == bookArray[i]){
        return true;
      }
    }
    return false;
  }
}

順便說一句,考慮您是否真正需要將==運算符與書本對象進行比較。

// If you declare this within the constructor, it'll be a local variable and nobody can access it. 
// Having it here means that inLibrary can see it
private Book[] bookArray;

Library(int maxBookCapacity){
    // watch out here, in your code you have a different var from the parameter of the constructor
    bookArray= new Book[maxBookCapacity];
}

boolean inLibrary(Book book){
    for(int i=0; i<bookArray.length; i++ ){
        if (book==bookArray[i]){
            return true;
        }
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM