輸入書本名稱,價格,對書本自動編号,可根據書本名稱,編号,價格查找相應書本
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("暫時未開放此功能...");
}
}
}