gpt4 book ai didi

java - 在java中将一本书的多个值添加到ArrayList中

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

我对如何将多个值添加到数组列表中有点困惑。

我想做的是将 1 个对象的多个值添加到数组列表中。

例如:

我有一个名为 books 的数组列表,我正在尝试添加一本书及其标题、作者、出版年份等...

这是我尝试过的地方,但我不确定它是否正确或是否有更简单的方法。

public class Book {

public static ArrayList<Book> Books = new ArrayList<>();

public int isbn;
public int yearPublished;
public String title;
public String author;
public String price;
public int noOfCopies;

Book b1 = new Book(1234, 1991, "Book1", "mark.mark", "£11.00", 5);
Book b2 = new Book(4321, 1994, "Book2", "bob.bob", "£12.00", 3);



public Book(int ISBN, int year, String ttle, String auth, String pri, int copies) {

this.isbn = ISBN;
this.yearPublished = year;
this.title = ttle;
this.author = auth;
this.price = pri;
this.noOfCopies = copies;

Books.add(this);
}
}

这是对的吗?有人可以帮我吗

最佳答案

你必须安排你的代码:

// Class Definition
public class Book {
// Member Variables
public int isbn;
public int yearPublished;
public String title;
public String author;
public String price;
public int noOfCopies;

// Constructor
public Book(int ISBN, int year, String ttle, String auth, String pri, int copies) {

this.isbn = ISBN;
this.yearPublished = year;
this.title = ttle;
this.author = auth;
this.price = pri;
this.noOfCopies = copies;
}

// Create a List of Books
public static List<Book> getBooks() {
Book b1 = new Book(1234, 1991, "Book1", "mark.mark", "£11.00", 5);
Book b2 = new Book(4321, 1994, "Book2", "bob.bob", "£12.00", 3);
List<Book> books = new ArrayList<Book>();
books.add(b1);
books.add(b2);
return books;
}
}

之后,您可以通过调用 getBooks() 函数来获取示例书籍:

List<Book> exampleBooks = Book.getBooks();

关于java - 在java中将一本书的多个值添加到ArrayList中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20667838/

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