一、需求描述
1、完成菜品的上架功能
2、完成菜品的浏览功能
二、开发设计
1、需要设计一个菜品类,用于创建菜品对象
2、需要一个菜品操作类,用于封装菜品上架和菜品浏览功能
3、测试程序
三、代码实现
3.1 Food类
package com.itheima.arraylist;
public class Food {
private String name;//菜品名称
private double price;//菜品价格
private String info;//菜品描述信息
public Food() {
}
public Food(String name, double price, String info) {
this.name = name;
this.price = price;
this.info = info;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
3.2 FoodOperator类
package com.itheima.arraylist;
import java.util.ArrayList;
import java.util.Scanner;
public class FoodOperator {
//菜品操作类,负责上架和浏览菜品
//定义一个ArrayList集合对象,负责存储菜品对象信息
private ArrayList<Food> foodlist = new ArrayList<>();
//上架菜品功能
public void addFood(){
//创建一个菜品对象
Food f = new Food();
//录入菜品信息
Scanner sc = new Scanner(System.in);
System.out.println("请输入菜品名称:");
String name = sc.next();
f.setName(name);
System.out.println("请输入菜品价格");
double price = sc.nextDouble();
f.setPrice(price);
System.out.println("请输入菜品描述");
String desc = sc.next();
f.setInfo(desc);
//添加信息到集合
foodlist.add(f);
System.out.println("上架成功");
}
//浏览菜品功能
public void showAllFoods(){
if (foodlist.size() == 0){
System.out.println("还没有菜品哦,请先去上架");
}
for (int i = 0; i < foodlist.size(); i++) {
Food f = foodlist.get(i);
System.out.println(f.getName());
System.out.println(f.getPrice());
System.out.println(f.getInfo());
System.out.println("--------------------");
}
}
public void start(){
Scanner sc = new Scanner(System.in);
while (true){
System.out.println("请选择功能:");
System.out.println("1-上架菜品");
System.out.println("2-展示菜品");
System.out.println("3-退出");
System.out.println("请输入你的选择:");
String command = sc.next();
switch (command){
case "1":
addFood();
break;
case "2":
showAllFoods();
break;
case "3":
System.out.println("欢迎下次再来");
return;
default:
System.out.println("您输入的命令不存在,请您重新输入!!!");
}
}
}
}
3.2 test
package com.itheima.arraylist;
import java.util.ArrayList;
public class ArrayListDemo2 {
public static void main(String[] args) {
//商家菜品上菜操作
//涉及一个菜品类food,负责创建菜品对象,封装菜品数据
FoodOperator operator = new FoodOperator();
operator.start();
}
}