//超市购物程序设计
//编写一个超市购物程序,实现超市购物功能。购物时,如果购物者所要购买的商品在超市中有,则提示购物者买到了某商品,如果没有购物者所需的商品,则提示购物者白跑了一趟
Product.java
public class Product {
private String name;
private double price;
private int count;
public Product() {
}
public Product(String name, double price, int count) {
this.name = name;
this.price = price;
this.count = count;
}
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 int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
Market.java
public class Market {
//超市名称
private String markName;
//储存商品
Product[] products=new Product[20];
public Market(){
}
public Market(String markName, Product[] products) {
this.markName = markName;
this.products = products;
}
public Product[] getProducts() {
return products;
}
public void setProducts(Product[] products) {
this.products = products;
}
public String getMarkName() {
return markName;
}
public void setMarkName(String markName) {
this.markName = markName;
}
//售出商品,需要有这个商品而且数量不为0才可以卖出
void sell(String name)
{
//根据名字找到这个商品
int flag=0;
for (Product product : products) {
if (name.equals(product.getName())) {
if (product.getCount() > 0) {
flag++;
System.out.println("买到了" + product.getName());
break;
}
}
}
if(flag==0)
{
System.out.println("白跑了一趟");
}
}
}
Person.java
public class Person {
//定义类的属性,用来描述对象的特征
//定义类的方法,来描述对象的行为
//每次买一件商品,该商品的数量-1
public void buy(String name,Market market){
market.sell(name);
}
}
Demo.java
public class Demo {
public static void main(String[] args) {
Product Apple=new Product("apple",13,5);
Product Computer=new Product("computer",5252,0);
Person person1=new Person();
Market spar=new Market("Spar", new Product[]{Apple, Computer});
person1.buy("apple",spar);
System.out.println("===================");
person1.buy("computer",spar);
}
}
原文:https://www.cnblogs.com/MirandaYuen/p/14255679.html