[英]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.