使用java写一个基于控制台的购书系统
时间: 2024-11-22 07:44:03 浏览: 15
在Java中编写一个简单的基于控制台的购书系统,可以模拟用户购买书籍的过程。这里是一个简化的示例,主要包括以下几个步骤:
```java
import java.util.Scanner;
class Book {
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public void displayBookInfo() {
System.out.println("Title: " + title);
System.out.println("Price: " + price);
}
}
class ShoppingCart {
private List<Book> books = new ArrayList<>();
public void addBook(Book book) {
books.add(book);
}
public void checkout(double totalBudget) {
double totalPrice = 0;
for (Book book : books) {
totalPrice += book.getPrice();
}
if (totalPrice <= totalBudget) {
System.out.println("Purchase successful. Total cost: " + totalPrice);
} else {
System.out.println("Insufficient budget. Total cost: " + totalPrice);
}
}
}
public class ConsoleBookStore {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Console Book Store!");
System.out.print("Enter your name: ");
String name = scanner.nextLine();
while (true) {
System.out.println("\n1. Add a book");
System.out.println("2. Checkout");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter book price: ");
double price = scanner.nextDouble();
Book book = new Book(title, price);
// Assuming you have access to a database or list of available books here
// For simplicity, we'll just hardcode one
Book availableBook = new Book("Book Title", 10.99); // Example book
ShoppingCart cart = new ShoppingCart();
cart.addBook(availableBook); // Assume the book is added to cart
break;
case 2:
System.out.print("Enter your budget: ");
double budget = scanner.nextDouble();
cart.checkout(budget);
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
```
在这个例子中,我们创建了`Book`类表示书籍,`ShoppingCart`类用于存储并计算总价,而`ConsoleBookStore`类则是主入口,处理用户的输入。用户可以选择添加书籍到购物车或结账。
阅读全文