gpt4 book ai didi

java - ArrayList 列出 null 而不是对象的实例

转载 作者:行者123 更新时间:2023-12-01 07:07:02 26 4
gpt4 key购买 nike

public class Library{
private ArrayList<Book> books = new ArrayList<Book>();

public void addBook()
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter title of the book: ");
String title = sc.nextLine();
System.out.println("Enter the author: ");
String author = sc.nextLine();

String bookID = bookID();

Book b = new Book(author,title,bookID,true);
books.add(b);

System.out.println( title + " by "+ author +" added to library.");
System.out.println("Book ID: " + bookID);

}

public void listBooks()
{
for (Book temp : books)
{
if (temp.loanStatus() == true) System.out.print("*");

System.out.println(temp.getTitle() + " by " + temp.getAuthor()+
"ID: " + temp.getID());
}
}
}

这是我的图书类(class):

public class Book {

private String author;
private String title;
private String ID;
private boolean loanRecord = true;

public Book(String au, String titl, String id, boolean loan)
{
au = author;
titl = title;
loan = loanRecord;
id = ID;
}

public String getTitle()
{
return title;
}

public String getAuthor()
{
return author;
}

public String getID()
{
return ID;
}

public boolean loanStatus()
{
return loanRecord;
}

public void checkoutBook()
{
loanRecord = false;
}

public void returnBook()
{
loanRecord = true;
}
}

出于某种原因,当我调用我的listBooks()时方法列出添加到 books 的所有书籍ArrayList,每个 Book我添加的对象显示为 null而不是我期望的所需字符串实例。

最佳答案

您在构造函数中交换了分配。

应该是:

public Book(String au, String titl, String id, boolean loan){   
author = au;
title = titl;
loanRecord = loan;
ID = id;
}

简单说一下,您可以重写 Book 类中的 toString 方法,然后简单地执行以下操作:

for (Book temp : books){
if (temp.loanStatus())
System.out.print("*");
System.out.println(temp);
}

关于java - ArrayList 列出 null 而不是对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21712636/

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