您的位置:首页 > 其它

4.22

2016-04-22 13:52 453 查看
public class ShopGoodsDemo {
public static void main(String[] args) {
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(gs[i].getName()+","+gs[i].getPrice());
sum=sum+gs[i].getPrice();
}
}
System.out.println("总价格为:"+sum);
}
}

public interface Goods {
public String getName();
public double getPrice();
}
public 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;
}
}
public 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;
}
}
public 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: