输入书本名称,价格,对书本自动编号,可根据书本名称,编号,价格查找相应书本
Book类
public class Book {
private int id;
private static int sid=1;
private String name;
private double price;
public Book(String name, double price) {
this.id = sid;
sid++;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
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;
}
@Override
public String toString() {
return "Book{" +
"编号=" + id +
", 书名='" + name + '\'' +
", 价格=" + price +
'}';
}
}
public class Tools {
Scanner input=new Scanner(System.in);
ArrayList<Book> books=new ArrayList<>();
public void add(){
System.out.print("请输入书本名称,");
// String name=input.next();
System.out.println("书本价格:");
// int price=input.nextInt();
Book book=new Book(input.next(),input.nextInt());
books.add(book);
System.out.println("添加成功");
}
public void showAll(){
Iterator<Book> it = books.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
public void selectBookForId(int seleid){
Iterator<Book> it = books.iterator();
Book book1;
while (it.hasNext()){
book1=it.next();
if (book1.getId()==seleid-1){
System.out.println(it.next());
}
}
}
public void selectBookForName(String selename){
Book book;
for (int i = 0; i <books.size(); i++) {
book=books.get(i);
if (selename.equals(book.getName()))
{
System.out.println(book.toString());
}
}
}
public void selectBookForPrice(double seleprice){
Book book;
for (int i = 0; i <books.size(); i++) {
book=books.get(i);
if (seleprice==book.getPrice()){
System.out.println(book.toString());
}
}
}
}
public class LibraryTest {
static Scanner input = new Scanner(System.in);
static Tools tools = new Tools();
public static void main(String[] args) {
System.out.println("---欢迎使用本图书系统---");
while (true) {
System.out.println("添加书请按1,查找书请按2,退出请按0");
int in = input.nextInt();
if (in == 1) {
addBook();
} else if (in == 2) {
selectBook();
} else if (in == 0) {
break;
} else {
System.out.println("暂时未开放此功能...");
}
}
tools.showAll();//最后显示所以书本
}
public static void addBook() {
for (int i = 0; i < 3; i++) {
System.out.println("一次输三本");
tools.add();
}
}
public static void selectBook(){
System.out.println("按编号查找请按1,书名请按2,价格请按3");
tools.showAll();
int select = input.nextInt();
if (select == 1) {
System.out.println("请输入图书编号:");
tools.selectBookForId(input.nextInt());
} else if (select == 2) {
System.out.println("请输入图书名称:");
String string = input.next();
tools.selectBookForName(string);
} else if (select == 3) {
System.out.println("请输入价格");
tools.selectBookForPrice(input.nextDouble());
} else {
System.out.println("暂时未开放此功能...");
}
}
}