gpt4 book ai didi

java - 图书馆和图书类,构造函数

转载 作者:行者123 更新时间:2023-12-01 18:11:11 25 4
gpt4 key购买 nike

为什么构造函数不读取库类数组中的元素?

当我调用一个元素(比如说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);


}
}

这是图书类:

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;
}

}

最佳答案

我假设 bookLibrary 应该保存图书馆的库存,即其中的书籍。在这种情况下,它必须是非静态的,因为您希望它为类(库)的每个实例存储不同的内容。

第二个问题是您将 bookLibrary 创建为空。总共可以存储 0 个元素(书籍)的数组将无法存储您尝试写入其中的四个元素。更重要的是,因为您是根据 bookLibrary 的长度进行迭代的。因此,您必须按照 bookLibrary=new Book[s.length];

的方式在构造函数中正确设置 bookLibrary 数组

关于java - 图书馆和图书类,构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com