用eclipse写一个食堂点餐程序
时间: 2023-09-25 07:11:10 浏览: 85
好的,下面是一个简单的食堂点餐程序的实现示例,使用 Eclipse 编写:
1. 创建一个 Java 项目,并添加以下类:
```java
/**
* 食堂点餐程序
*/
public class MealOrderingSystem {
public static void main(String[] args) {
// 初始化食品菜单
Menu menu = new Menu();
menu.addFood(new Food("炒饭", 10));
menu.addFood(new Food("炒面", 12));
menu.addFood(new Food("麻婆豆腐", 15));
menu.addFood(new Food("红烧肉", 18));
// 初始化顾客订单
Order order = new Order();
// 展示菜单
menu.showMenu();
// 点餐
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请选择菜品编号(输入 0 结束点餐):");
int foodIndex = scanner.nextInt();
if (foodIndex == 0) {
break;
}
Food food = menu.getFood(foodIndex - 1);
if (food != null) {
order.addFood(food);
System.out.println("已点:" + food.getName());
} else {
System.out.println("菜品编号有误,请重新选择!");
}
}
// 展示订单
order.showOrder();
}
}
/**
* 菜单类
*/
class Menu {
private List<Food> foods = new ArrayList<>();
/**
* 添加菜品
*/
public void addFood(Food food) {
foods.add(food);
}
/**
* 获取菜品
*/
public Food getFood(int index) {
if (index >= 0 && index < foods.size()) {
return foods.get(index);
}
return null;
}
/**
* 展示菜单
*/
public void showMenu() {
System.out.println("欢迎来到食堂,请选择以下菜品:");
for (int i = 0; i < foods.size(); i++) {
System.out.println((i + 1) + ". " + foods.get(i).getName() + "(" + foods.get(i).getPrice() + "元)");
}
}
}
/**
* 菜品类
*/
class Food {
private String name;
private int price;
public Food(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
/**
* 订单类
*/
class Order {
private List<Food> foods = new ArrayList<>();
/**
* 添加菜品
*/
public void addFood(Food food) {
foods.add(food);
}
/**
* 展示订单
*/
public void showOrder() {
System.out.println("您的订单如下:");
int totalPrice = 0;
for (int i = 0; i < foods.size(); i++) {
System.out.println((i + 1) + ". " + foods.get(i).getName() + "(" + foods.get(i).getPrice() + "元)");
totalPrice += foods.get(i).getPrice();
}
System.out.println("总价:" + totalPrice + "元");
}
}
```
2. 运行程序,在控制台中选择菜品编号添加到订单中,输入 0 结束点餐,最后展示订单信息。
阅读全文