提示信息

Java保存图书信息

舔伤 已关注

要保存图书信息,可以创建一个Book类,该类包含以下属性:
- ID:图书的唯一标识符
- Title:图书的标题
- Author:图书的作者
- Year:图书的出版年份

然后,可以使用一个ArrayList来存储图书对象。在程序中,可以通过以下方式保存图书信息:

  1. 创建Book类:
  1. public class Book {
  2. private int ID;
  3. private String title;
  4. private String author;
  5. private int year;
  6. public Book(int ID, String title, String author, int year) {
  7. this.ID = ID;
  8. this.title = title;
  9. this.author = author;
  10. this.year = year;
  11. }
  12. // Getters and setters
  13. public int getID() {
  14. return ID;
  15. }
  16. public void setID(int ID) {
  17. this.ID = ID;
  18. }
  19. public String getTitle() {
  20. return title;
  21. }
  22. public void setTitle(String title) {
  23. this.title = title;
  24. }
  25. public String getAuthor() {
  26. return author;
  27. }
  28. public void setAuthor(String author) {
  29. this.author = author;
  30. }
  31. public int getYear() {
  32. return year;
  33. }
  34. public void setYear(int year) {
  35. this.year = year;
  36. }
  37. }
  1. 创建一个类来保存图书信息的 ArrayList:
  1. import java.util.ArrayList;
  2. public class BookManager {
  3. private ArrayList<Book> bookList;
  4. public BookManager() {
  5. bookList = new ArrayList<>();
  6. }
  7. public void addBook(Book book) {
  8. bookList.add(book);
  9. }
  10. public boolean removeBook(int ID) {
  11. for (int i = 0; i < bookList.size(); i++) {
  12. if (bookList.get(i).getID() == ID) {
  13. bookList.remove(i);
  14. return true;
  15. }
  16. }
  17. return false;
  18. }
  19. public Book findBook(int ID) {
  20. for (Book book : bookList) {
  21. if (book.getID() == ID) {
  22. return book;
  23. }
  24. }
  25. return null;
  26. }
  27. public ArrayList<Book> getAllBooks() {
  28. return bookList;
  29. }
  30. }
  1. 在主程序中使用BookManager类来保存图书信息:
  1. public class Main {
  2. public static void main(String[] args) {
  3. BookManager bookManager = new BookManager();
  4. // 添加图书
  5. Book book1 = new Book(1, "Java编程思想", "Bruce Eckel", 2006);
  6. Book book2 = new Book(2, "Effective Java", "Joshua Bloch", 2018);
  7. bookManager.addBook(book1);
  8. bookManager.addBook(book2);
  9. // 删除图书
  10. bookManager.removeBook(2);
  11. // 查找图书
  12. Book foundBook = bookManager.findBook(1);
  13. if (foundBook != null) {
  14. System.out.println("找到图书:" + foundBook.getTitle());
  15. } else {
  16. System.out.println("未找到图书");
  17. }
  18. // 获取所有图书
  19. ArrayList<Book> allBooks = bookManager.getAllBooks();
  20. for (Book book : allBooks) {
  21. System.out.println("图书信息:" + book.getTitle());
  22. }
  23. }
  24. }

上述代码演示了如何使用Book和BookManager类来保存、查找和删除图书信息。你可以根据需要对代码进行修改和扩展。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
舔伤 关注 已关注

最近一次登录:2023-10-09 13:15:43   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图