java写一个外卖订餐系统程序中的菜品列表、订单列表、顾客列表等都必须采用所学过的一种数据结构(链表、栈、队列、树等)存储,不能全部只使用数组。
时间: 2023-07-04 17:22:51 浏览: 191
好的,下面是一个使用链表存储数据的外卖订餐系统的Java代码示例:
```java
import java.util.*;
public class Restaurant {
private String name;
private List<MenuItem> menu;
public Restaurant(String name) {
this.name = name;
this.menu = new LinkedList<>();
}
public void addMenuItem(MenuItem item) {
menu.add(item);
}
public void displayMenu() {
System.out.println("Menu for " + name + ":");
for (MenuItem item : menu) {
System.out.println(item.getName() + "\t" + item.getPrice());
}
}
public void placeOrder(Order order) {
double totalCost = 0;
for (MenuItem item : order.getItems()) {
totalCost += item.getPrice();
}
order.setTotalCost(totalCost);
System.out.println("Order placed. Total cost: " + totalCost);
}
}
public class MenuItem {
private String name;
private double price;
public MenuItem(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
public class Order {
private List<MenuItem> items;
private double totalCost;
public Order(List<MenuItem> items) {
this.items = items;
}
public List<MenuItem> getItems() {
return items;
}
public double getTotalCost() {
return totalCost;
}
public void setTotalCost(double totalCost) {
this.totalCost = totalCost;
}
}
public class Customer {
private String name;
private List<Order> orderHistory;
public Customer(String name) {
this.name = name;
this.orderHistory = new LinkedList<>();
}
public void placeOrder(Restaurant restaurant, List<MenuItem> items) {
Order order = new Order(items);
restaurant.placeOrder(order);
orderHistory.add(order);
}
public void displayOrderHistory() {
System.out.println("Order history for " + name + ":");
for (Order order : orderHistory) {
System.out.println("Restaurant: " + order.getRestaurantName() + "\tTotal cost: " + order.getTotalCost());
}
}
}
public class Main {
public static void main(String[] args) {
// 创建餐厅和菜品
Restaurant restaurant = new Restaurant("Restaurant Name");
MenuItem item1 = new MenuItem("Item 1", 10);
MenuItem item2 = new MenuItem("Item 2", 20);
restaurant.addMenuItem(item1);
restaurant.addMenuItem(item2);
// 创建顾客
Customer customer = new Customer("Customer Name");
// 浏览餐厅菜单
restaurant.displayMenu();
// 下单
List<MenuItem> items = new LinkedList<>();
items.add(item1);
items.add(item2);
customer.placeOrder(restaurant, items);
// 查看订单历史记录
customer.displayOrderHistory();
}
}
```
在这个示例中,我们使用了Java中的`LinkedList`来存储菜品列表、订单列表和顾客列表。这使得我们可以灵活地添加、删除和遍历列表中的元素。
阅读全文