学习日志day13(2021-07-26)(1、使用集合完成点餐系统)

学习内容:学习JavaSE(Day13)

1、使用集合完成点餐系统


1、使用集合完成点单系统

(1)两个类之间互相调用时,两个对象在全局变量中相互引用,可能会出现就异常StackOverflowError。
原因 : 函数调用栈太深了,注意代码中是否有了循环调用方法而无法退出的情况。

public class OrderingController {
    private UserService userService = new UserService();
}
public class UserService {
	public OrderingController oc = new OrderingController();
}

可以实例化成局部变量进行使用,但是不推荐这样使用,在调用的时候会出现重复定义同一个对象或集合的情况,将之前存入的数据覆盖掉:

public void login() {
	OrderingController oc = new OrderingController();
	oc.secondMenu(user);
}

(2)初始化菜品时,可以使用静态块的方法进行初始化,然后在其它类中调用dishesList集合进行展示:

public static List<Dishes> dishesList = new ArrayList<Dishes>()
static{
      Dishes dishes1 = new Dishes(1,"鱼香肉丝",29.9,0);
      Dishes dishes2 = new Dishes(2,"糖醋里脊",19.9,0);
      Dishes dishes3 = new Dishes(3,"糖醋排骨",39.9,0);
      Dishes dishes4 = new Dishes(4,"口味茄子",19.9,0);
      Dishes dishes5 = new Dishes(5,"干锅土豆片",39.9,0);
      Dishes dishes6 = new Dishes(6,"歌乐山辣子鸡",59.9,0);

      dishesList.add(dishes1);
      dishesList.add(dishes2);
      dishesList.add(dishes3);
      dishesList.add(dishes4);
      dishesList.add(dishes5);
      dishesList.add(dishes6);
  }

也可以使用方法进行初始化:

public static List<Dishes> dishesList = initDishes();
private static List<Dishes> initDishes() {
    List<Dishes> dishesList2 = new ArrayList<>();
    Dishes dishes1 = new Dishes(1,"鱼香肉丝",29.9,0);
    Dishes dishes2 = new Dishes(2,"糖醋里脊",19.9,0);
    Dishes dishes3 = new Dishes(3,"糖醋排骨",39.9,0);
    Dishes dishes4 = new Dishes(4,"口味茄子",19.9,0);
    Dishes dishes5 = new Dishes(5,"干锅土豆片",39.9,0);
    Dishes dishes6 = new Dishes(6,"歌乐山辣子鸡",59.9,0);

    dishesList2.add(dishes1);
    dishesList2.add(dishes2);
    dishesList2.add(dishes3);
    dishesList2.add(dishes4);
    dishesList2.add(dishes5);
    dishesList2.add(dishes6);

    return  dishesList2;
}

(3)在菜品实体类中重写toString方法,方便打印出菜品。

@Override
public String toString() {
    return id + "\t\t\t\t" + dishesName + "\t\t\t\t" + price + "\t\t\t\t" + praiseNum;
}
for (Dishes dishes : dishesList) {
    System.out.println(dishes);
}

如果不重写toString方法,打印出来内容如下:
com.hisoft.entity.Dishes@29774679
com.hisoft.entity.Dishes@3ffc5af1
com.hisoft.entity.Dishes@5e5792a0
com.hisoft.entity.Dishes@26653222

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值