gpt4 book ai didi

java - 新手: how to save and print objects in Java?

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

很抱歉这个新手问题,但我刚刚开始编程,而且这个东西很复杂。

我有以下代码摘录,用于创建 Book 类型的对象来构建我的库。

 public class Library {

public static void main(String[] args) {

int bookID = 0;
String title;
String author;
int printDate;


Book book1 = new Book(bookID++, "Book title example", "Book author example", 1990);
Book book2 = new Book(bookID++, "Another book title", "Another author", 1992);

// Now lets print the available book titles in my library
for (int i = 1; i <= bookID; i++)
System.out.println(book[i].title);

}
}

当然,这不起作用,但我不确定如何处理所有对象以立即打印它们。

解决方案似乎是将所有 Book 对象信息发送到某种数组,然后打印数组内容。

但是如果我想向图书馆添加新书,那么我必须构建一个新数组,而这似乎不是最好的方法。

此外,每当程序初始化时,bookID 将始终为 0。但是,如果有一种方法可以强制 bookID 变量始终包含最后引入的 bookID,那么我在为每本书设置 ID 时就不必使用 bookID++ 运算符。它只会从某处读取(也许是包含对象信息的数组?)并向新对象添加一个值。

抱歉,这可能很简单,但我几周前才开始学习。

谢谢!

最佳答案

It seems the solution would be to send all the Book objects info to some kind of array, and then print the array contents.

But if I want to add new books to the library, then I have to build a new array, and this doesn't seem like the best way to do it.

java.util 包已经有一堆用于处理对象列表、集合等的类。检查 java.util.Collection 的子类。

Also, whenever the program initializes, the bookID will always be at 0. But if there is a way to force the bookID variable to always contain the last introduced bookID, then I wouldn't have to use the bookID++ operator when setting the ID for each book. It would just read from somewhere (maybe that array that contains object info?) and add one value to the new Object.

您必须将其存储在某个地方。文件、数据库等等。首先尝试使用文件。当然,您必须自己编写/更新文件的内容。

关于java - 新手: how to save and print objects in Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16749425/

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