使用java编写一个基于控制台的购书系统包括书的编号,书名,单价,库存
时间: 2024-11-23 07:40:30 浏览: 33
好的,我们可以创建一个简单的基于控制台的购书系统,使用Java语言。这个系统可以包含Book类表示书籍,以及相关的操作如添加、查看和购买等。以下是简化的代码结构:
```java
// 定义Book类
class Book {
private int bookId;
private String title;
private double price;
private int stock;
public Book(int id, String name, double price, int stock) {
this.bookId = id;
this.title = name;
this.price = price;
this.stock = stock;
}
// 获取和设置属性的方法
public int getBookId() { return bookId; }
public void setBookId(int bookId) { this.bookId = bookId; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public int getStock() { return stock; }
public void setStock(int stock) { this.stock = stock; }
}
// 控制台操作类
public class ConsoleShop {
private List<Book> books = new ArrayList<>();
// 添加书籍
public void addBook(Book book) {
books.add(book);
}
// 查看书籍信息
public void viewBooks() {
for (Book book : books) {
System.out.println("书编号: " + book.getBookId() +
", 书名: " + book.getTitle() +
", 单价: " + book.getPrice() +
", 库存: " + book.getStock());
}
}
// 购买书籍
public void purchaseBook(int bookId, int quantity) {
for (Book book : books) {
if (book.getBookId() == bookId && book.getStock() >= quantity) {
book.setStock(book.getStock() - quantity);
System.out.println("已购买 " + quantity + "本《" + book.getTitle() + "》");
} else {
System.out.println("无法购买,该书无货或库存不足");
}
}
}
}
// 主程序入口
public static void main(String[] args) {
ConsoleShop shop = new ConsoleShop();
// 初始化并添加书籍...
shop.addBook(new Book(1, "Java基础", 50.0, 20));
// ...其他书籍
// 操作系统示例
shop.viewBooks(); // 显示所有书籍信息
shop.purchaseBook(1, 5); // 购买书籍
}
```
阅读全文