为什么构造函数不读取库类数组中的元素?
当我调用一个元素时,让我们说csBooks[3]
,我就会变成垃圾。
public class Library {
String address;
public static Book[] bookLibrary = {};
public Library(String location, Book[] s){
address = location;
for(int i = 0; i < bookLibrary.length-1; i++){
bookLibrary[i] = s[i];
}
public static void main(String[] args) {
// Create two libraries
Book [] books = {new Book("The Da Vinci Code"),
new Book("Le Petit Prince"),
new Book("A Tale of Two Cities"),
new Book("The Lord of the Rings")};
Book [] csBooks = {new Book("Java for Dummies"),
new Book("Operating Systems"),
new Book("Data Structures in Java"),
new Book("The Lord of the Rings")};
Library firstLibrary = new Library("535 W114th St.", books);
Library secondLibrary = new Library("1214 Amsterdam Av.", csBooks);
}
}
这是Book Class:
public class Book {
String title;
boolean borrowed;
// Creates a new Book
public Book(String bookTitle) {
//Implement this method
title = bookTitle;
borrowed = false;
}
// Marks the book as rented
public void borrowed() {
//Implement this method
borrowed = true;
}
// Set the book to borrowed
public void rented() {
//Implement this method
borrowed = true;
}
// Marks the book as not rented
public void returned() {
//Implement this method
borrowed = false;
}
// Returns true if the book is rented, false otherwise
public boolean isBorrowed() {
//Implement this method
if(borrowed){
return true;
} else {
return false;
}
}
// Returns the title of the book
public String getTitle() {
//Implement this method
return title;
}
}
答案 0 :(得分:2)
我假设bookLibrary
应该保存图书馆的库存,即那里的书籍。在这种情况下,它必须是非静态的,因为你希望它为类(库)的每个实例存储不同的东西。
第二个问题是您创建了bookLibrary
- 数组为空。一个可以存储总共0个元素(书籍)的数组将无法存储您尝试写入其中的四个元素。更重要的是,因为你根据bookLibrary的长度进行迭代。因此,您必须在bookLibrary=new Book[s.length];
答案 1 :(得分:2)
您的代码在几个部分中是错误的 - 至少,您有一个静态字段。
但是,要回答你的“为什么不读它”的问题,请看这一部分:
public Library(String location, Book[] s) {
for(int i = 0; i < bookLibrary.length-1; i++){
bookLibrary[i] = s[i];
}
}
在构造函数调用期间, bookLibrary.length - 1
等于-1
,并且循环根本不会迭代。
可能应该s.length
这样吗?
public Library(String location, Book[] s) {
for(int i = 0; i < s.length; i++) {
bookLibrary[i] = s[i];
}
}
为什么-1
?它不会影响最后一个元素。
P.S。我不擅长Java - 我是C#开发人员。可能这是一个语言问题,但为什么你不能做(假设bookLibrary
不再是静态的):
public Library(String location, Book[] s) {
bookLibrary = s;
}
答案 2 :(得分:0)
因为
public static Book[] bookLibrary = {};
在两个实例之间共享。 它不应该是静态的。