java基于控制台的图书购买系统
时间: 2023-10-04 21:14:07 浏览: 107
好的,我可以为您提供一个简单的Java控制台图书购买系统,您可以根据自己的需求进行修改和扩展。
首先,我们需要定义一个Book类,用于表示一本书的属性和行为:
```java
public class Book {
private String title;
private String author;
private double price;
private int stock;
public Book(String title, String author, double price, int stock) {
this.title = title;
this.author = author;
this.price = price;
this.stock = stock;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getPrice() {
return price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public String toString() {
return String.format("%s - %s (%.2f元) 库存:%d本", title, author, price, stock);
}
}
```
接下来,我们创建一个BookStore类,用于管理图书库存和购买流程:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class BookStore {
private ArrayList<Book> books;
public BookStore() {
books = new ArrayList<Book>();
}
public void addBook(Book book) {
books.add(book);
}
public void listBooks() {
System.out.println("当前库存图书:");
for (Book book : books) {
System.out.println(book.toString());
}
}
public void buyBook() {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要购买的书籍名称:");
String title = scanner.nextLine();
Book targetBook = null;
for (Book book : books) {
if (book.getTitle().equals(title)) {
targetBook = book;
break;
}
}
if (targetBook == null) {
System.out.println("未找到该书籍!");
return;
}
System.out.print("请输入购买数量:");
int num = scanner.nextInt();
if (num > targetBook.getStock()) {
System.out.println("库存不足!");
return;
}
double totalPrice = targetBook.getPrice() * num;
System.out.printf("购买成功,共花费%.2f元。", totalPrice);
targetBook.setStock(targetBook.getStock() - num);
}
}
```
最后,我们在Main函数中创建一个BookStore对象,添加几本图书,然后进入主循环,等待用户输入命令:
```java
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BookStore store = new BookStore();
store.addBook(new Book("Java编程思想", "Bruce Eckel", 99.0, 10));
store.addBook(new Book("Effective Java", "Joshua Bloch", 89.0, 20));
store.addBook(new Book("Head First 设计模式", "Eric Freeman", 69.0, 15));
while (true) {
System.out.println("\n请选择操作:");
System.out.println("1. 查看库存");
System.out.println("2. 购买书籍");
System.out.println("3. 退出系统");
System.out.print(">> ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
store.listBooks();
break;
case 2:
store.buyBook();
break;
case 3:
System.out.println("欢迎下次再来!");
return;
default:
System.out.println("无效操作!");
break;
}
}
}
}
```
这样,一个简单的Java控制台图书购买系统就完成了。您可以根据自己的需求进行修改和扩展,例如添加更多的图书属性、增加管理员登录功能等等。
阅读全文