第七次做業

 

interface Goods{
public String getName();
public double getPrice();
}
 class EatFood implements Goods{
private String name;
private double price;
public EatFood() {

}
public EatFood(String name, double price) {
super();
this.name = name;
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
 class WashGoods implements Goods{
private String name;
private double price;
public WashGoods() {

}
public WashGoods(String name, double price) {
super();
this.name = name;
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
class ShopCar {
private Goods goods[]=null;
private int foot;

//數組的大小由程序外部決定
public ShopCar(int len) {
if(len>0){
goods=new Goods[len];
}else{
goods=new Goods[1];
}
}

//判斷數組的內容是否已滿,未滿,則添加
public boolean add(Goods g){
if(this.foot<this.goods.length){
this.goods[foot]=g;
foot++;
return true;
}else{
return false;
}
}
         //關鍵字查找
public Goods[] search(String keyword){
  Goods go[]=null;
  int count=0;
for(int i=0;i<this.goods.length;i++){
         if(goods[i]!=null){
         if(this.goods[i].getName().indexOf(keyword)!=-1){
         count++;
             }
         }
}
go=new Goods[count];
        int f=0;
for(int i=0;i<this.goods.length;i++){
        if(goods[i]!=null){
if(this.goods[i].getName().indexOf(keyword)!=-1){
        go[f]=this.goods[i];
f++;
}
}
}
return go;
}
//獲得所有信息
public Goods[] getGoods(){
return this.goods;    
}
}
public class JavaSix {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ShopCar s1=new ShopCar(5);
        s1.add(new EatFood("麪包",12.1));
        s1.add(new EatFood("辣條",2.4));
        s1.add(new EatFood("餅乾",22.3));
        s1.add(new WashGoods("洗髮水",32.5));
        s1.add(new WashGoods("衛生紙",22.8));
        print(s1.search("餅乾"));
        System.out.println("=============");
        print(s1.getGoods());
        }
        public static void print(Goods gs[]){
        double sum=0;
        for(int i=0;i<gs.length;i++){
        if(gs[i]!=null){
        //System.out.println(p[i]+",");
        System.out.println(gs[i].getName()+","+gs[i].getPrice());
        sum=sum+gs[i].getPrice();    
        }
        }
        System.out.println("總價格爲:"+sum);
        }
        
    }
相關文章
相關標籤/搜索