赞
踩
参考代码:
Book.java:
public class Book { private int id; private String name; private String author; private double price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Book(int id, String name, String author, double price) { this.id = id; this.name = name; this.author = author; this.price = price; } @Override public String toString() { return "Book{id="+id+"\tname="+name+"\tauthor="+author+"\tprice="+price+"}"; } }
Manager.java:
public class Manager { //定义一个集合来存储图书信息 private ArrayList<Book> list = new ArrayList<>(); /** * 添加图书 * @param book */ public void add(Book book){ list.add(book); } /** * 修改--根据书名修改价格 * @param name * @param price */ public void update(String name,double price){ for (int i = 0; i < list.size(); i++) { Book book = list.get(i); if (name.equals(book.getName())){ book.setPrice(price); System.out.println("修改成功:"+book); } } } /** * 根据id删除图书 * @param id */ public void delete(int id){ for (int i = 0; i < list.size(); i++) { Book book = list.get(i); if (id==book.getId()){ list.remove(book); System.out.println("删除成功"); } } } /** * 查询--根据id查询图书信息 * @param id */ public Book query(int id){ for (int i = 0; i < list.size(); i++) { Book book = list.get(i); if (id==book.getId()){ System.out.println(book); return book; } } return null; } /** * 查询--根据图书名称查询图书信息 * @param name */ public Book query(String name){ for (int i = 0; i < list.size(); i++) { Book book = list.get(i); if (name.equals(book.getName())){ System.out.println(book); return book; } } return null; } /** * 展示所有图书信息 */ public void showAll(){ for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } /** * 按照价格降序排序 */ public void sort(){ Collections.sort(list, new Comparator<Book>() { @Override public int compare(Book o1, Book o2) { return -(int)(o1.getPrice()-o1.getPrice()); } }); } }
Test.java:
public static void main(String[] args) { //实例manager对象 Manager manager = new Manager(); //添加书籍 manager.add(new Book(1,"三国演义","罗贯中",97.5)); manager.add(new Book(2,"水浒传","施耐庵",67)); manager.add(new Book(3,"西游记","吴承恩",76)); manager.add(new Book(4,"红楼梦","曹雪芹",50)); manager.add(new Book(5,"金瓶梅","兰陵笑笑生",25)); //根据id查询图书 manager.query(03); //根据图书名称查询 manager.query("三国演义"); //根据名称修改价格 manager.update("金瓶梅",55); //删除图书 manager.delete(5); //排序 manager.sort(); manager.showAll(); } }
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。