文档详情

APP应用开发包(初级)第十章.ppt

发布:2018-02-12约4.08千字共18页下载文档
文本预览下载声明
APP应用开发包(初级) --第十章 -----孔美云 任务 宠物商店 4 情境描述 1 2 3 问题分析 解决方案 知识总结 5 应用实践 1 情境描述 设计一个“宠物商店”,在宠物商店中可以有多种(由用户决定数量)宠物,试表示出此种关系,并要求可以根据宠物的关键字查找到相应的宠物信息。 2 问题分析 (1)本要求中提示宠物的信息可以自行设计,所以此时简单设计出名字、颜色、年龄3个属性。 (2)宠物的类别很多,如猫、狗等都属于宠物,所以宠物应该是一个标准。 (3)在宠物商店中,只要是符合了此宠物标准的就都应该可以放进宠物商店之中。 (4)宠物商店中要保存多种宠物,则肯定应该是一个宠物的对象数组,如果宠物的个数由用户决定,则应该在创建宠物商店时,就已经分配好宠物的个数。 分析图 宠物商店不管具体的宠物是哪一个,只要是宠物就可以放进去,所以此宠物的标准应该使用接口进行定义,每个具体的宠物都实现此接口,宠物商店与接口有关 . 类图 宠物商店———PetShop.java ,定义宠物商店的操作类,在宠物商店中应该包含一个宠物接口的对象数组 . class PetShop{ // 宠物商店 private Pet[] pets ; // 保存一组宠物 private int foot ; public PetShop(int len){ if(len0){ this.pets = new Pet[len] ; // 开辟数组大小 }else{ this.pets = new Pet[1] ; // 至少开辟一个空间 } } public boolean add(Pet pet){ // 增加的是一个宠物 if(this.footthis.pets.length){ this.pets[this.foot] = pet ; // 增加宠物 this.foot ++ ; return true ; }else{ return false ; } } 3 解决方案 public Pet[] search(String keyWord){ // 应该确定有多少个宠物符合要求 Pet p[] = null ; int count = 0 ; // 记录下会有多少个宠物符合查询结果 for(int i=0;ithis.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;ithis.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 ; } } 3 解决方案 3 解决方案 测试宠物商店———PetShopDemo.java 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)) ; // 增加宠物,失败 print(ps.search(黑)) ; } 3 解决方案
显示全部
相似文档