Java保存图书信息
要保存图书信息,可以创建一个Book类,该类包含以下属性:
- ID:图书的唯一标识符
- Title:图书的标题
- Author:图书的作者
- Year:图书的出版年份
然后,可以使用一个ArrayList来存储图书对象。在程序中,可以通过以下方式保存图书信息:
- 创建Book类:
public class Book {
private int ID;
private String title;
private String author;
private int year;
public Book(int ID, String title, String author, int year) {
this.ID = ID;
this.title = title;
this.author = author;
this.year = year;
}
// Getters and setters
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
- 创建一个类来保存图书信息的 ArrayList:
import java.util.ArrayList;
public class BookManager {
private ArrayList<Book> bookList;
public BookManager() {
bookList = new ArrayList<>();
}
public void addBook(Book book) {
bookList.add(book);
}
public boolean removeBook(int ID) {
for (int i = 0; i < bookList.size(); i++) {
if (bookList.get(i).getID() == ID) {
bookList.remove(i);
return true;
}
}
return false;
}
public Book findBook(int ID) {
for (Book book : bookList) {
if (book.getID() == ID) {
return book;
}
}
return null;
}
public ArrayList<Book> getAllBooks() {
return bookList;
}
}
- 在主程序中使用BookManager类来保存图书信息:
public class Main {
public static void main(String[] args) {
BookManager bookManager = new BookManager();
// 添加图书
Book book1 = new Book(1, "Java编程思想", "Bruce Eckel", 2006);
Book book2 = new Book(2, "Effective Java", "Joshua Bloch", 2018);
bookManager.addBook(book1);
bookManager.addBook(book2);
// 删除图书
bookManager.removeBook(2);
// 查找图书
Book foundBook = bookManager.findBook(1);
if (foundBook != null) {
System.out.println("找到图书:" + foundBook.getTitle());
} else {
System.out.println("未找到图书");
}
// 获取所有图书
ArrayList<Book> allBooks = bookManager.getAllBooks();
for (Book book : allBooks) {
System.out.println("图书信息:" + book.getTitle());
}
}
}
上述代码演示了如何使用Book和BookManager类来保存、查找和删除图书信息。你可以根据需要对代码进行修改和扩展。