java基于控制台的购书系统代码
时间: 2024-10-11 09:03:24 浏览: 30
开发基于控制台的购书系统_java源代码.doc
创建一个简单的基于控制台的购书系统代码通常涉及用户界面交互、书籍管理以及购买操作。这里是一个基本的伪代码示例,展示了如何设计这样的系统:
```java
import java.util.Scanner;
class Book {
String title;
double price;
// 构造函数,getters和setters省略
}
class ShoppingCart {
private List<Book> items = new ArrayList<>();
void addItem(Book book) {
items.add(book);
}
void removeItem(Book book) {
items.remove(book);
}
double getTotalCost() {
return items.stream().mapToDouble(Book::price).sum();
}
}
public class ConsoleBookStore {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Book book1 = new Book("《Java核心技术》", 50.0);
Book book2 = new Book("《算法导论》", 80.0);
ShoppingCart cart = new ShoppingCart();
System.out.println("欢迎来到购书系统!");
while (true) {
System.out.println("请选择操作:1.添加书籍 2.删除书籍 3.查看购物车 4.结账");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("请输入书籍标题:");
String title = scanner.next();
System.out.print("请输入价格:");
double price = scanner.nextDouble();
Book selectedBook = new Book(title, price);
cart.addItem(selectedBook);
break;
// ...其他case处理...
case 4:
if (cart.getTotalCost() > 0) {
System.out.printf("总价:%.2f元\n", cart.getTotalCost());
// 结账过程(比如清空购物车)
cart.getItems().clear();
} else {
System.out.println("购物车为空");
}
break;
default:
System.out.println("无效选择,请重试");
break;
}
}
}
}
```
阅读全文