写一个java项目基于面向对象编程,基于控制台的购书系统,实现购书功能。程序运行输出所有图书的信息,包括书的编号,书名,单价,库存。 顾客购书时,根据提示输入图书编号选购需要的书,并根据提示输入需要购买书的数量,购买完毕输出顾客的订单信息,包括订单号,订单明细,订单总额。
时间: 2024-10-22 21:07:53 浏览: 32
在Java中创建一个简单的购书系统,我们可以设计如下的类结构:
1. **Book** 类:
```java
public class Book {
private int id;
private String title;
private double price;
private int stock;
// 构造函数、getter和setter
public Book(int id, String title, double price, int stock) {
this.id = id;
this.title = title;
this.price = price;
this.stock = stock;
}
// 显示书籍信息的方法
public void display() {
System.out.println("ID: " + id + ", Title: " + title + ", Price: " + price + ", Stock: " + stock);
}
}
```
2. **Catalog** 类(库存管理类):
```java
import java.util.ArrayList;
public class Catalog {
private ArrayList<Book> books;
public Catalog() {
books = new ArrayList<>();
// 添加一些示例书籍
addBook(new Book(1, "Book1", 10.99, 5));
addBook(new Book(2, "Book2", 15.99, 3));
}
// 其他方法如添加书籍、删除书籍等
// 添加书籍的方法
public void addBook(Book book) {
books.add(book);
}
// 显示所有书籍信息的方法
public void displayAllBooks() {
for (Book book : books) {
book.display();
}
}
}
```
3. **Customer** 类:
```java
public class Customer {
private int orderId;
// 购买方法
public void purchase(Book book, int quantity) {
if (book.stock >= quantity) {
book.decreaseStock(quantity);
System.out.println("Order ID: " + orderId++ + ", Order Detail: " + book.getTitle() + " x " + quantity + ", Total: $" + quantity * book.getPrice());
} else {
System.out.println("Not enough stock for this book.");
}
}
// 减少库存的方法
public static void decreaseStock(Book book, int decreaseBy) {
book.stock -= decreaseBy;
}
}
```
4. **Main** 类:
```java
public class Main {
public static void main(String[] args) {
Catalog catalog = new Catalog();
catalog.displayAllBooks();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter book ID to buy or 'exit' to quit: ");
int inputId = scanner.nextInt();
if (inputId == -1) break;
Book selectedBook = catalog.searchBookById(inputId);
if (selectedBook != null) {
System.out.print("Enter the quantity: ");
int quantity = scanner.nextInt();
Customer customer = new Customer();
customer.purchase(selectedBook, quantity);
} else {
System.out.println("Invalid book ID.");
}
}
scanner.close();
}
// 搜索书籍的方法
public static Book searchBookById(Catalog catalog, int id) {
return catalog.books.stream().filter(book -> book.getId() == id).findFirst().orElse(null);
}
}
```
阅读全文