代码分析
import java.util.*;
public class Main { //主函数
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Market mk=new Market();
mk.setName(in.next());
mk.addProduct(new Product("电视机"));
mk.addProduct(new Product("洗衣机"));
mk.addProduct(new Product("豆浆机"));
mk.addProduct(new Product("打印机"));
mk.addProduct(new Product("大便"));
//String name=in.next();
Person p=new Person();
p.setName("张乐");
p.shopping(mk, new Product(in.next()));
}
}
class Product { //商品类
private String name;
public Product(String name) {
this.name=name;
}
public void setName(String name) {//set get
this.name=name;
}
public String getName() {
return name;
}
}
class Market {
private String name;
private Product[] products = new Product[0];//创建数组
public void setName(String name) { //set get
this.name=name;
}
public String getName() {
return name;
}
public void addProduct(Product name) { //添加商品
products=Arrays.copyOf(products, products.length+1);
products[products.length-1]=name;
}
public String sell(String name) { //查找商品是否存在
for(Product product:products) {
if(product.getName().equals(name)) return name;
}
return null;
}
}
class Person{
private String name; //常规set get
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void shopping(Market a,Product b) { //查货
if(a.sell(b.getName())==null) System.out.printf("%s所需要的商品无货\n",name);
else System.out.printf("%s买到了%s\n",name,b.getName());
}
}