动物乐园包括的成员:猫、鸭子……
属性:名称、腿方法:叫
设计类图
再加入一个海豚类:
需求说明:
1.分别创建Cat、Duck、Dolphin对象并放到一个数组中,编写方法对数组进行遍历输出各种动物如何叫
2.对数组进行遍历输出各种动物腿的条数
3.增加修改功能,使用户可以修改三种动物的信息
4. 如果腿的条数不符合客观条件则手动抛出异常,调用此方法时捕捉异常
编程实现:
1.动物类
//动物类public abstract class Animal {//定义名字和腿数类型private String name;private int legNum;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getLegNum() {return legNum;}public void setLegNum(int legNum) {this.legNum = legNum;}public Animal() {}public Animal(String name, int legNum) {this.name = name;this.legNum = legNum;}//动物叫的抽象方法public abstract String shout();}
2.子类猫类
//子类猫类public class Cat extends Animal {public Cat(){}public Cat(String name,int legNum){super(name,legNum);}public String shout() {return "喵喵喵...";}}
3.子类鸭子类
//子类鸭子类public class Duck extends Animal {public Duck(){}public Duck(String name,int legNum){super(name,legNum);}public String shout() {return "嘎嘎嘎...";}}
4.子类海豚类
//子类海豚类public class Dolphin extends Animal {public Dolphin(){}public Dolphin(String name,int legNum){super(name,legNum);}public String shout() {return "海豚音...";}}
5.用户类:定义显示、修改、判断等方法
import java.util.Scanner;//用户类:定义显示、修改、判断等方法public class Custom {Scanner input = new Scanner(System.in);int xiugai;//判断是否修改String newName;//修改后的新名字Animal cat = new Cat();Animal duck = new Duck();Animal dolphin = new Dolphin();//定义Animal数组存进去各种动物信息Animal[] animal ={new Cat("加菲猫",4),new Duck("唐小鸭",2),new Dolphin("海豚奇奇",0)};//输出所有动物信息public void xianshi(){System.out.println("动物名字\t腿的条数\t动物叫");for(int i=0;i<animal.length;i++){System.out.println(animal[i].getName()+"\t"+animal[i].getLegNum()+"\t"+animal[i].shout());}}//修改想要修改的动物信息public void xiugai(String oldName,String newName,int legNum) throws Exception{if(oldName.equals(animal[0].getName())){if(legNum==4){animal[0].setName(newName);}else{throw new Exception("猫有4条腿");}}else if(oldName.equals(animal[1].getName())){if(legNum==2){animal[1].setName(newName);}else{throw new Exception("鸭有2条腿");}}else if(oldName.equals(animal[2].getName())){if(legNum==0){animal[2].setName(newName);}else{throw new Exception("海豚没有腿");}}System.out.println("是否要继续修改数据:按0进行修改,其他任意数字键退出");xiugai= input.nextInt();}//判断想要填入的新的动物信息是否重复public void panduan(){boolean pan = false;String new1Name;do{System.out.println("请输入修改后的动物名称:");new1Name=input.next();for(int i = 0;i<animal.length;i++){if(animal[i].getName().equals(new1Name)){System.out.println("输入错误请重新输入");pan = true;}else{pan = false;}}}while(pan == true);newName = new1Name;}}
6.测试类
import java.util.Scanner;//测试类public class Test {public static void main(String[] args) {Scanner input = new Scanner(System.in);Custom c = new Custom();do{c.xianshi();System.out.println("请输入要修改的动物姓名:");String oldName=input.next();c.panduan();System.out.println("这个动物有几条腿:");int legNum=input.nextInt();try {c.xiugai(oldName, c.newName, legNum);} catch (Exception e) {e.printStackTrace();}}while(c.xiugai==0);if(c.xiugai !=0 ){System.out.println("谢谢使用!");}}}