定义图书类Book,具有属性账号id,书名name、作者author 和价格price和一个图书馆类Library保存新书

时间:2025-03-10 16:04:04
/** * @author:fang */ package shixun.project1.zuoye1; import java.util.*; public class Library { public static void main(String[] args) { HashSet<Book> hashSet=new HashSet<>(); select(hashSet); // addBook(); } //功能选择 private static void select(HashSet<Book> hashSet) { Scanner s=new Scanner(System.in); System.out.println("功能列表:\n1.插入图书\n2.删除图书\n3.修改图书\n4.查看图书\n请输入对应id选择功能:"); String opt=s.next(); switch (opt){ case "1": hashSet=addBook(hashSet); break; case "2": deleteBook(hashSet); break; case "3": changeBook(hashSet); break; case "4": checkBook(hashSet); break; default: System.out.println("输入错误,请重新输入!"); select(hashSet); } } //增 private static HashSet<Book> addBook(HashSet<Book> hashSet) { ArrayList<Book> arrayList=new ArrayList<>(hashSet); Scanner s=new Scanner(System.in); do { System.out.println("插入图书:"); System.out.println("input bookId:"); int id=s.nextInt(); System.out.println("input bookName:"); String name=s.next(); System.out.println("input bookAuthor:"); String author=s.next(); System.out.println("input bookPrice"); double price=s.nextDouble(); hashSet.add(new Book(id,name,author,price)); System.out.println("是否继续插入y/N?"); String isNext=s.next(); if (isNext.equals("n")){ System.out.println("插入完毕!"); select(hashSet); break; } else { if (!isNext.equals("y")) { System.out.println("请输入正确的指令!"); select(hashSet); break; } System.out.println(hashSet); } }while (true); checkBook(hashSet); return hashSet; } //删 private static HashSet<Book> deleteBook(HashSet<Book> hashSet) { System.out.println("删除图书"); System.out.println("请输入要删除书籍的ID:"); Scanner s=new Scanner(System.in); int deleteId=s.nextInt(); ArrayList<Book> arrayList=new ArrayList<>(hashSet); Collections.sort(arrayList); Iterator<Book> iterator=arrayList.iterator(); while (iterator.hasNext()){ Book b=(Book) iterator.next(); if(b.getId()==deleteId){ iterator.remove(); } } //这里稍微需要注意一下,因为CRUD返回的都是HashSet,所以把删除后的arrayList里面的值重新倒给hashSet,进行输出和返回 hashSet=new HashSet<Book>(arrayList); checkBook(hashSet); select(hashSet); return hashSet; } //改 private static void changeBook(HashSet<Book> hashSet) { System.out.println("修改图书"); select(hashSet); } //查 private static void checkBook(HashSet<Book> hashSet) {//,HashSet<Book> hashSet System.out.println("查看图书"); ArrayList<Book> arrayList=new ArrayList<>(hashSet); Collections.sort(arrayList); Iterator<Book> iterator=arrayList.iterator(); while (iterator.hasNext()){ Book book = (Book) iterator.next(); System.out.println(book); } select(hashSet); } }