1 public class Market {
2 // 1. 定义超市名称的字符串变量
3 // 因为String是大写了 首字母 所以它是类 又因为类的默认值是null 所以String的默认值就是null
4 private String marketName;
5 // 2. 定义的是仓库 类型:产品类型的数组
6 private Product[] productArray;
7 public String getMarketName(){return marketName;}
8 // market.setMarketName("旺财");
9 public void setMarketName(String marketName){ // 紫色 名称 = 黑色名称 “旺财”
10 this.marketName = marketName;
11 }
12
13 public Product[] getProductArray() {
14 return productArray;
15 }
16 public void setProductArray(Product[] productArray){
17 this.productArray = productArray;
18 }
19
20 /**
21 * 售货方法
22 * 返回值类型:因为卖的是一个商品、因此返回值是一个商品
23 * @param name 指定的商品名称
24 * @return 如果有商品 会返回商品、 没有商品 会返回空
25 */
26 public Product sell(String name){// name 就应该是 霸王洗发水
27 for (int i = 0; i < productArray.length; i++) {
28 if (productArray[i].getProductName().equals(name)){
29 return productArray[i];
30 }
31 }
32 return null;
33 }
34 }
1 /*
2 人
3 */
4 public class Person {
5 // 1. 定义 人名
6 private String name;
7 // 2. 生成对应的getter和setter方法
8 public String getName(){
9 return name;
10 }
11 public void setName(String name){
12 this.name = name;
13 }
14
15 /**
16 * 购物
17 * @param market 超市对象
18 * @param productName 买什么商品
19 * @return
20 */
21 public Product shopping(Market market, String productName){// 大润发
22 // 超市有一个方法叫做 卖货方法 参数是 买什么商品
23 // return market.sell(霸王洗发水);
24 return market.sell(productName);
25 }
26 }
1 /*
2 产品的类
3 */
4 public class Product {
5 // 1. 定义产品名称/商品名称
6 public String productName;
7 // 2. 生成对应的getter和setter方法
8 public String getProductName(){
9 return productName;
10 }
11 public void setProductName(String productName){
12 this.productName = productName;
13 }
14 }
1 import java.util.Scanner;
2
3 public class TestMarket {
4 public static void main(String[] args) {
5
6 // 1. 创建对象 商品对象
7 Product p1 = new Product();
8 Product p2 = new Product();
9 Product p3 = new Product();
10 Product p4 = new Product();
11 Product p5 = new Product();
12
13 // 2. 设置商品名称
14 p1.setProductName("霸王");
15 p2.setProductName("电冰箱");
16 p3.setProductName("电脑");
17 p4.setProductName("洗衣机");
18 p5.setProductName("空调");
19
20 // 3. 创建超市对象
21 Market m1 = new Market();
22 Market m2 = new Market();
23
24 m1.setMarketName("大润发");
25 m1.setProductArray(new Product[]{p1,p2,p3,p4,p5});
26
27 m2.setMarketName("家家悦");
28 m2.setProductArray(new Product[]{p1,p2,p4,p5});
29
30 // 4. 创建消费者对象
31 Person p = new Person();
32 p.setName("旺财");
33
34 Scanner sc = new Scanner(System.in);
35 System.out.println("请输入您需要购买商品的名称:");
36 String wantBuy = sc.nextLine();
37
38 Product result = p.shopping(m1,wantBuy);
39
40 if (result != null){
41 // 买到
42 System.out.println(p.getName()+"去"+m1.getMarketName()+"买到了"+result.getProductName());
43 }else {
44 // 没有买到
45 System.out.println(p.getName()+"去"+m1.getMarketName()+"什么都没有买到");
46 }
47 }
48 }