基于控制台的购书系统java代码
时间: 2024-10-14 13:11:53 浏览: 20
基于控制台的购书系统通常是一个简单的命令行交互程序,用于模拟用户购买书籍的过程。以下是使用Java编写的一个简化的示例:
```java
import java.util.Scanner;
class Book {
String title;
double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public void displayBook() {
System.out.println("Title: " + title);
System.out.println("Price: " + price);
}
}
public class ShoppingCart {
private double totalPrice;
private Book currentBook;
public void addToCart(Book book) {
if (currentBook == null) {
currentBook = book;
} else {
currentBook = new Book(currentBook.getTitle(), currentBook.getPrice());
}
totalPrice += book.getPrice();
System.out.println("Added " + book.title + " to cart. Total Price: " + totalPrice);
}
public void checkout() {
if (currentBook != null) {
System.out.println("Purchased: " + currentBook.title);
System.out.println("Total Price: " + totalPrice);
currentBook = null; // 清空购物车
totalPrice = 0;
} else {
System.out.println("No books in the cart.");
}
}
}
public class ConsoleBookShop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ShoppingCart cart = new ShoppingCart();
while (true) {
System.out.println("\nChoose an action: 1. Add a book 2. Checkout 3. Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter book title: ");
String title = scanner.next();
System.out.print("Enter book price: ");
double price = scanner.nextDouble();
Book book = new Book(title, price);
cart.addToCart(book);
break;
case 2:
cart.checkout();
break;
case 3:
System.out.println("Goodbye!");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
```
在这个例子中,`Book`类代表书籍,`ShoppingCart`类管理购物车和总价。`ConsoleBookShop`是主入口,它通过`Scanner`接收用户的输入,并根据用户的指令操作购物车。
阅读全文