在idea平台上开发一个java小项目,入门级别的。
这个程序可以在控制台上实现展示菜单、点菜、结账三个功能。
public class DishApp {
//定义集合 表示小饭店拥有的菜品
static List<Dish> dishList = new ArrayList<>();
static List<Dish> personDish = new ArrayList<>();//用户已点的菜品的集合
public static void main(String[] args) {
initDish();
//创建扫描器对象,获取到控制台输入的内容
Scanner s = new Scanner(System.in);
//写死循环
while (true){
ShowMenu();
//展示之后要获取编号
int num = s.nextInt();
switch (num){
case 1:
while (true){ //点菜不是一次性操作
showDishMenu();
int id = s.nextInt();
if(id==0){break;}
Dish dish = dishList.get(id-1);//集合的索引是0开始的
System.out.println("您下单了"+dish.name);
personDish.add(dish);
}
case 2:
showPeopleDish();
break;//结束switch循环
case 3:
buy();
return; //结束while循环
}
}
}
public static void showDishMenu(){
System.out.println("-----请您点菜----");
for (int i = 0; i < dishList.size(); i++) {
Dish dish = dishList.get(i);
System.out.println(dish.id+"\t"+dish.name+"\t"+dish.price);
}
System.out.println("----输入序号点菜,按0返回上一级-----");
}
public static void showPeopleDish(){
System.out.println("----您已经点了的菜品-----");
for(Dish dish:personDish){
System.out.println(dish.id+"\t"+dish.name+"\t"+dish.price);
}
}
public static void buy(){
System.out.println("----请稍等,正在结算。。。-----");
double total = 0f;
for(Dish dish:personDish){
total+= dish.price;
}
System.out.println("您本次消费了"+total+"元");
}
public static void ShowMenu(){
System.out.println("------主菜单-----");
System.out.println("菜单\t\t\t 1");
System.out.println("已点菜品\t\t 2");
System.out.println("买单\t\t\t 3");
System.out.println("--------根据编号请选择服务-------");
}
public static void initDish(){
Dish dish1 = new Dish(1,"鱼香肉丝",29.0);
Dish dish2 = new Dish(2,"炖王八",59.0);
Dish dish3 = new Dish(3,"烤羊腿",65.0);
Dish dish4 = new Dish(4,"米饭",2.0);
Dish dish5 = new Dish(5,"地三鲜",26.0);
dishList.add(dish1);
dishList.add(dish2);
dishList.add(dish3);
dishList.add(dish4);
dishList.add(dish5);
}
}
特别注意的是,这个代码块中用两个while死循环实现了主菜单和菜单循环展示的功能。
其中,我们需要把Dish这个类封装起来。
public class Dish {
int id;
String name;
double price;
//生成有参的构造方法
public Dish(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
}
|