作业:
有一个中餐厅,有一些厨师,负责包包子,有一些顾客来买包子,统计餐厅的收入。
包子类:
package lession220713;
/**
* @author 123 包子类
*/
public class Bun {
private static float PRICE = 2.5f;// 包子价格
public float getPRICE() {
return PRICE;
}
public static void setPRICE(float pRICE) {
PRICE = pRICE;
}
}
厨师类:
package lession220713;
/**
* 厨师类
*
* @author 123
*
*/
public class Chef{
// 厨师所在餐厅
private final Restaurant restaurant;
public Chef(Restaurant restaurant) {
this.restaurant = restaurant;
}
/**
* 做包子
* @param n
*/
public void makebun(int n){
for(int i=0;i<n;i++) {
Bun bun = new Bun();
this.restaurant.addBun(bun);
}
}
}
顾客类:
package lession220713;
/**
* 顾客类
* @author 123
*
*/
public class Customer {
private String name;//顾客姓名
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
餐厅类:
package lession220713;
/**
* 餐厅类
*
* @author 123
*
*/
public class Restaurant {
private Bun[] bun = new Bun[100];
private int bunIdx = 0;// 用于指向当前有多少个包子,可能会达到数组的长度
private Chef[] chefs;// 餐厅的所有厨师
private float total;// 餐厅的总收入
/**
* 向餐厅添加包子
*
* @param bun
*/
public void addBun(Bun bun) {
if (bunIdx < this.bun.length) {//最多做100个包子
this.bun[bunIdx] = bun;
bunIdx++;
}
}
/**
* 开门营业
*
*/
public void start() {
for (int i = 0; i < chefs.length; i++) {
chefs[i].makebun((int) (Math.random() * 20));//每个厨师随机做0-20个包子
}
}
/**
* 卖包子
*
* @param c
* @param n
*/
public void sell(Customer c, int n) {
float total = 0;// 本次的收入
for (int i = 0; i < n; i++) {
if (bunIdx < 1) {//如果包子数小于0,退出循环
break;
}
total += bun[bunIdx - 1].getPRICE();
bunIdx--;//包子数减1
}
this.total += total;// 计算总收益
}
public Bun[] getBun() {
return bun;
}
public void setBun(Bun[] bun) {
this.bun = bun;
}
public int getBaoIdx() {
return bunIdx;
}
public void setBaoIdx(int baoIdx) {
this.bunIdx = baoIdx;
}
public Chef[] getChef() {
return chefs;
}
public void setChef(Chef[] chef) {
this.chefs = chef;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
}
主类:
package lession220713;
public class Test {
public static void main(String[] args) {
Restaurant r = new Restaurant();
Chef[] chefs = new Chef[10];//设置10个厨师
for (int i = 0; i < chefs.length; i++) {
Chef c = new Chef(r);//创建10个厨师对象
chefs[i] = c;
}
r.setChef(chefs);//把厨师对象穿到餐厅类的厨师数组中
r.start();//调用方法开始营业
System.out.println("餐厅现有" + r.getBaoIdx() + "个包子");
int n = (int) (Math.random() * 20);//设置一个0-20的随机数当做顾客数
for (int i = 0; i < n; i++) {
Customer cust = new Customer();
cust.setName(f1(3));//随机给顾客姓名赋值为3个字母
int m = (int) (Math.random() * 5 + 1);// 一个顾客买的包子数为1-6
System.out.println("顾客" + cust.getName() + "买" + m + "个包子");
r.sell(cust, m);//调用卖包子的方法
}
System.out.println("餐厅总收入:" + r.getTotal() + "元");
System.out.println("餐厅现有" + r.getBaoIdx() + "个包子");
}
private static String f1(int n) {//随机生成3个小写字母的字符串
String s = new String();
for (int i = 0; i < n; i++) {
char c = (char) (Math.random() * 25 + 97);
s += c;
}
return s;
}
}
输出结果: