標籤:interface 部落格目錄 介面 寵物商店 介面設計的一個程式執行個體寵物商店
外延 以往寫部落格沒有用那種目錄的結構,今天終於會用了。如何使用目錄結構請參照:目錄結構的使用 執行個體要求 實現一個寵物商店,寵物商店的寵物可以有多種(數量由使用者決定),試表示此種關係,並要求根據寵物的的關鍵字尋找寵物的資訊,所需要的寵物資訊自行設計。 所用知識 介面,對象數組 執行個體分析 寵物資訊可以自行設計,我們可以簡單設計三個屬性:名字、顏色、年齡 寵物的類別很多、所以寵物應該是一個標準(介面) 寵物商店有多種寵物,應該是一個寵物的對象數組 代碼實現
interface Pet{// 定義寵物介面public String getName() ;public String getColor() ;public int getAge() ;}class Cat implements Pet{// 貓是寵物,實現介面private String name ;// 寵物名字private String color ;// 寵物顏色private int age ;// 寵物年齡public Cat(String name,String color,int age){this.setName(name) ;this.setColor(color) ;this.setAge(age) ;}public void setName(String name){this.name = name ;}public void setColor(String color){this.color = color;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public String getColor(){return this.color ;}public int getAge(){return this.age ;}};class Dog implements Pet{// 狗是寵物,實現介面private String name ;// 寵物名字private String color ;// 寵物顏色private int age ;// 寵物年齡public Dog(String name,String color,int age){this.setName(name) ;this.setColor(color) ;this.setAge(age) ;}public void setName(String name){this.name = name ;}public void setColor(String color){this.color = color;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public String getColor(){return this.color ;}public int getAge(){return this.age ;}};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 add(Pet pet){// 增加的是一個寵物if(this.foot<this.pets.length){this.pets[this.foot] = pet ;// 增加寵物this.foot ++ ; //foot 數組下標return true ;}else{return false ;}}public Pet[] search(String keyWord){// 應該確定有多少個寵物符合要求Pet p[] = 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||this.pets[i].getColor().indexOf(keyWord)!=-1){count++ ;// 修改尋找到的記錄數}}}p = new Pet[count] ;// 開闢指定的大小空間int f = 0 ;// 增加元素的位置標記for(int i=0;i<this.pets.length;i++){if(this.pets[i]!=null){// 表示此位置有寵物if(this.pets[i].getName().indexOf(keyWord)!=-1||this.pets[i].getColor().indexOf(keyWord)!=-1){p[f] = this.pets[i] ;f++ ;}}}return p ;}};public class PetShopDemo{public static void main(String args[]){PetShop ps = new PetShop(5) ;// 五個寵物ps.add(new Cat("白貓","白色的",2)) ;// 增加寵物,成功ps.add(new Cat("黑貓","黑色的",3)) ;// 增加寵物,成功ps.add(new Cat("花貓","花色的",3)) ;// 增加寵物,成功ps.add(new Dog("拉步拉多","黃色的",3)) ;// 增加寵物,成功ps.add(new Dog("金毛","金色的",2)) ;// 增加寵物,成功ps.add(new Dog("黃狗","黑色的",2)) ;// 增加寵物,失敗 數組長度為5print(ps.search("黑")) ;}public static void print(Pet p[]){for(int i=0;i<p.length;i++){if(p[i]!=null){System.out.println(p[i].getName() + "," + p[i].getColor()+"," + p[i].getAge()) ;}}}};
總結 本程式最主要的是介面的設計, 注意查詢時indexof的使用,程式設計要嚴謹(一些判斷的使用)。
介面設計的一個程式執行個體(寵物商店)