用java写一个基于控制台的购书系统
时间: 2024-09-11 18:15:33 浏览: 49
开发基于控制台的购书系统_java源代码.doc
创建一个基于控制台的购书系统需要考虑几个基本要素,包括图书信息的存储、用户界面以及购物流程。下面是一个简单的Java购书系统实现的示例:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class BookStore {
private Map<String, Book> bookCatalog = new HashMap<>();
private Map<String, Integer> shoppingCart = new HashMap<>();
private Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
BookStore store = new BookStore();
store.loadBooks();
store.run();
}
private void loadBooks() {
// 这里可以添加代码,从文件读取或者数据库加载图书信息到bookCatalog
}
private void run() {
boolean exit = false;
while (!exit) {
System.out.println("欢迎来到购书系统");
System.out.println("1. 查看图书");
System.out.println("2. 购买图书");
System.out.println("3. 结算");
System.out.println("4. 退出");
System.out.print("请输入选项:");
int option = scanner.nextInt();
scanner.nextLine(); // 读取换行符
switch (option) {
case 1:
showBooks();
break;
case 2:
buyBook();
break;
case 3:
checkout();
break;
case 4:
exit = true;
break;
default:
System.out.println("无效的选项,请重新输入!");
}
}
}
private void showBooks() {
for (Map.Entry<String, Book> entry : bookCatalog.entrySet()) {
Book book = entry.getValue();
System.out.println("书名: " + book.getTitle() + " 作者: " + book.getAuthor() + " 价格: " + book.getPrice());
}
}
private void buyBook() {
System.out.print("请输入要购买的书名:");
String bookName = scanner.nextLine();
Book book = bookCatalog.get(bookName);
if (book != null) {
int quantity = 0;
while (quantity <= 0) {
System.out.print("请输入购买数量:");
try {
quantity = scanner.nextInt();
if (quantity <= 0) {
System.out.println("数量必须大于0,请重新输入!");
}
} catch (Exception e) {
System.out.println("输入错误,请输入一个有效的数量!");
scanner.next(); // 清除错误输入
}
}
shoppingCart.put(bookName, shoppingCart.getOrDefault(bookName, 0) + quantity);
System.out.println("已添加 " + quantity + " 本 " + bookName + " 到购物车。");
} else {
System.out.println("抱歉,我们没有这本书。");
}
}
private void checkout() {
if (shoppingCart.isEmpty()) {
System.out.println("您的购物车是空的。");
return;
}
System.out.println("结算中...");
for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
Book book = bookCatalog.get(entry.getKey());
int quantity = entry.getValue();
double totalPrice = book.getPrice() * quantity;
System.out.println("书名: " + book.getTitle() + " 数量: " + quantity + " 总价: " + totalPrice);
}
shoppingCart.clear();
System.out.println("结算完成,感谢您的购买!");
}
}
class Book {
private String title;
private String author;
private double price;
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getPrice() {
return price;
}
}
```
在这个简单的购书系统中,我们定义了两个类:`BookStore`和`Book`。`BookStore`类包含了图书目录和购物车的管理,以及主方法。`Book`类用于存储图书信息。系统提供了查看图书、购买图书和结算的功能。
请注意,这个示例是一个非常基础的实现,没有考虑错误处理、持久化存储和用户输入的复杂情况。在实际应用中,你可能需要添加更多的功能和健壮性考虑,比如异常处理、图书库存管理、用户身份验证、支付处理等。
阅读全文