用java写一个外卖订餐系统并且用队列
时间: 2024-04-30 18:20:11 浏览: 107
Java开发的一个外卖点餐系统源码.zip
好的,下面是一个简单的外卖订餐系统的Java代码,使用了队列进行订单的管理:
```java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Order {
private String name;
private String address;
private String phone;
public Order(String name, String address, String phone) {
this.name = name;
this.address = address;
this.phone = phone;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
@Override
public String toString() {
return "Name: " + name + ", Address: " + address + ", Phone: " + phone;
}
}
public class FoodDeliverySystem {
private static Queue<Order> orders = new LinkedList<>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("1. Place an order");
System.out.println("2. View orders");
System.out.println("3. Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
placeOrder();
break;
case 2:
viewOrders();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invalid choice!");
break;
}
}
}
private static void placeOrder() {
scanner.nextLine(); // consume the newline character
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your address: ");
String address = scanner.nextLine();
System.out.print("Enter your phone number: ");
String phone = scanner.nextLine();
Order order = new Order(name, address, phone);
orders.add(order);
System.out.println("Order placed successfully!");
}
private static void viewOrders() {
if (orders.isEmpty()) {
System.out.println("No orders yet!");
return;
}
System.out.println("Orders:");
for (Order order : orders) {
System.out.println(order);
}
}
}
```
在这个代码中,我们定义了一个`Order`类来表示订单,其中包含了客户的姓名、地址和电话号码等信息。我们使用了`LinkedList`作为队列的实现,通过调用`add()`方法来向队列中添加订单,使用`isEmpty()`方法来判断队列是否为空,使用`forEach()`方法来遍历队列中的订单。在`placeOrder()`方法中,我们通过`Scanner`类来获取用户输入的订单信息。在`main()`方法中,我们使用了一个无限循环来实现菜单的循环显示,当用户选择退出时,我们调用了`System.exit()`方法来终止程序的运行。
阅读全文