思路:创建三各类 books 相当于书类 记录着书的属性和获取书的方法 mannagerbooks 管理图书 里面创建的一个books类型的数组 相当于书架 里面实现增删改查的方法 TestBooks 测试类记录着调各个类的方法实现菜单。
package com.hainiu.book; import java.util.Scanner; //书的属性类 class Books{ private String name; private double price; private int number; public Books(){ } public Books(String name, double price, int number) { this.name = name; this.price = price; this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String show(){ return name +","+ price + "," + number; } } class ManagerBooks{ //创建一个数组 相当于书架存放book private Books [] books = new Books[100]; //添加 public void add(Books book){ //循环查看书架 如果没有这本书 那么增加 如果有那么提示已经有这本书了 for (int i = 0; i < books.length; i++) { if(books[i]==null){ books[i]=book; System.out.println("添加成功"); break; }else{ System.out.println("该书已存在"); } } } //修改 public void update(int number,double price){ //循环查看书架 如果有这本书 那么修改 如果没有提示没有这本书 for (int i = 0; i < books.length; i++) { if(books[i].getNumber()==number){ //如果有这个编号 那么改他的价格 books[i].setPrice(price); System.out.println("修改成功"); }else{ System.out.println("该书不存在"); } break; } } //删除 public void delete(int number){ for (int i = 0; i < books.length; i++) { if(books[i].getNumber()==number){ //数组删除用后一个覆盖前一个 for (int j = i; j < books.length-1; j++) { books[j]=books[j+1]; } if(books[books.length-1]!=null){ books[books.length-1]=null; } System.out.println("删除成功"); break; } } } //查询 public void query(){ System.out.println("图书编号\t图书名称 \t图书价格"); for (Books b : books) { if(b == null){ break; } System.out.println(b.show()); } } //退出 } public class TestBooks { public void startsystem(){ Scanner sc = new Scanner(System.in); ManagerBooks mgb = new ManagerBooks(); System.out.println("-----欢迎来到菜单-----"); System.out.println("1、添加 2、修改 3、删除 4、查询 5、退出"); int number; String name; double price; while(true){ System.out.println("请选择菜单"); //录入数字的 int n =sc.nextInt(); switch(n){ //如果是1 那么就是添加 name +","+ price + "," + number; case 1: System.out.println("欢迎来到添加页面"); System.out.println("请输入编号"); number = sc.nextInt(); System.out.println("请输入书名"); name = sc.next(); System.out.println("请输入价格"); price = sc.nextDouble(); Books books = new Books( name, price, number); mgb.add(books); break; //如果是2那么就是修改页面 case 2: System.out.println("欢迎来到修改页面"); System.out.println("输入要修改的编号"); number = sc.nextInt(); System.out.println("输入改的价格"); price = sc.nextDouble(); mgb.update(number, price); break; case 3: System.out.println("欢迎来到删除页面"); System.out.println("输入要删除的编号"); number = sc.nextInt(); mgb.delete(number); break; case 4: System.out.println("欢迎来到查询页面"); mgb.query(); break; case 5: System.out.println("退出页面"); System.exit(0); } } } public static void main(String[] args) { // TODO Auto-generated method stub new TestBooks().startsystem(); } }