赞
踩
实体方法类:
- public class Test {
- public static void main(String[] args) {
- //1.设计一个菜品类Food,负责创建菜品对象,封装菜品数据
- //2.设计一个菜品操作类foodOperator,负责完成对菜品的业务实现:上架、浏览
- foodOperator operator=new foodOperator();
- operator.start();
-
- }
- }
对象:
- package arrayListTest;
-
- public class Food {
- private String name;
- private double price;
- private String desc; //描述
- //2.创建有参无参构造器
-
- public Food() {
- }
-
- public Food(String name, double price, String desc) {
- this.name = name;
- this.price = price;
- this.desc = desc;
- }
-
- //1.创建getter setter方法
- 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 getDesc() {
- return desc;
- }
-
- public void setDesc(String desc) {
- this.desc = desc;
- }
- }
实体操作类:
- import java.util.ArrayList;
- import java.util.Scanner;
-
- public class foodOperator {
- //1.定义一个ArrayList集合对象,负责储存菜品对象信息
- ArrayList<Food> foods=new ArrayList<>();
- //foods=[]
-
- //2.开发功能:上架菜品功能
- public void addFood(){
- //3.创建一个菜品对象,封装上架的菜品信息
- Food f=new Food();
-
- //4把菜品信息录入进去
- 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.setDesc(desc);
-
- //5.把菜品对象存入到集合中去
- foods.add(f);
- System.out.println("上架成功!");
- }
- //6.展示菜品
- public void showAllFoods(){
- if (foods.size()==0){
- System.out.println("什么菜品都没有,请先上架~");
- return;
- }//如果用户直接输入2查询没有菜品信息,拦截
- for (int i = 0; i < foods.size(); i++) {
- Food f=foods.get(i);
- System.out.println(f.getName());
- System.out.println(f.getPrice());
- System.out.println(f.getDesc());
- System.out.println("-----------------");
- }
- }
- // 负责展示操作界面。
- public void start(){
- while (true) {
- System.out.println("请选择功能:");
- System.out.println("1、上架菜品");
- System.out.println("2、展示菜品");
- System.out.println("3、退出");
- Scanner sc=new Scanner(System.in);
- 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("您输入的命令不存在!");
- }
- }
-
- }
- }
运行效果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。