1定义宠物标准,用一个pet接口 package petshop; public interface Pet { public String getName(); public int getAge(); public float getPrice(); } 2定义宠物商店,其中可定义宠物个数,增加宠物数量,查询宠物 package petshop; public class PetShop { private Pet[] pets;//表示有多个宠物 private int foot; public PetShop(int len){ //宠物个数可通过外部指定 if(len>0){ this.pets=new Pet[len]; } else{ this.pets=new Pet[1]; //至少保留一个宠物 } } public Boolean addPet(Pet p){ //增加宠物 if(this.foot<pets.length){ //如果角标小于限定的宠物数量则可以增加宠物 this.pets[foot]=p; //保存宠物 this.foot++; //角标增加 return true; //增加成功 } else{ return false; //增加失败 } } //查询时可能返回多个内容,还应该以数组的形式返回 public Pet[] search(String keyword){ //根据关键字查询 Pet[] result=null; //声明数组,大小不确定 int count=0; //记录有多少种宠物符合信息 for(int i=0;i<this.pets.length;i++){ if(this.pets[i]!=null){ //表示有宠物信息 if(this.pets[i].getName().indexOf(keyword)!=-1){ //查询到了结果 count++; } } } result=new Pet[count]; //根据查出的个数开辟数组空间 count=0; //加入内容 for(int i=0;i<this.pets.length;i++){ if(this.pets[i]!=null){ //表示有宠物信息 if(this.pets[i].getName().indexOf(keyword)!=-1){ //查询到了结果 result[count]=this.pets[i]; //返回查询的结果 count++; } } } return result; } } 3定义宠物猫,宠物狗 //宠物猫 package petshop; public class Cat implements Pet { public String name; public int age; public float price; public Cat(String name, int age, float price) { this.name = name; this.age = age; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String toString() { return "宠物猫的名字:"+this.getName()+",年龄:"+ this.getAge()+",价格:"+this.getPrice(); } } //宠物狗 package petshop; public class Dog implements Pet { public String name; public int age; public float price; public Dog(String name, int age, float price) { this.name = name; this.age = age; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @Override public String toString() { return "宠物狗的名字:"+this.getName()+",年龄:"+ this.getAge()+",价格:"+this.getPrice(); } } 4建立测试类,测试类之间的关系 package petshop; public class TestPetShop { public static void main(String[] args) { PetShop shop=new PetShop(5); //定义能存放5个宠物的商店 shop.addPet(new Cat("黑猫",3,89.4f)); //增加宠物成功 shop.addPet(new Cat("白猫",2,34.4f)); shop.addPet(new Cat("花猫",4,76.4f)); shop.addPet(new Dog("白狗",1,123.5f)); shop.addPet(new Dog("黑狗",5,23.5f)); shop.addPet(new Dog("死狗",6,3.5f)); //增加失败 Pet[] p=shop.search("狗"); for(int i=0;i<p.length;i++){ System.out.println(p[i]); } } } |