面向对象第七章上机练习

				面向对象第七章上机练习
package tang.biao;

public abstract class Animal {
	private String name;
	public Animal(){

	}
	    public Animal(String name){
	    this.setName(name);
	    
	    }
	public String getName() {
	return name;
	}

	public void setName(String name) {
	this.name = name;
	}

	   public abstract String shout();
	}
package tang.biao;

public class Cat extends Animal implements Terrestrial{
	private int legNum;
	@Override
	public int getlegNum() {
		// TODO 自动生成的方法存根
		return legNum;
	}
package tang.biao;

public class Duck extends Animal implements Terrestrial{
	private int legNum;
	  
	@Override
	public int getlegNum() {
		// TODO 自动生成的方法存根
		return legNum;
	}

	public void setLegNum(int legNum) {
	this.legNum = legNum;
	}
	        public Duck(){
	        
	        }
	public  Duck(String name,int legNum){
	super(name);
	this.setLegNum(legNum);

	}
	public String shout(){
	return "嘎嘎嘎";
	}


	}
package tang.biao;

public class Dolphin extends Animal {

	public Dolphin(String name) {
		super(name);
	
	}

	@Override
	public String shout() {
		// TODO 自动生成的方法存根
		return "海豚音";
	}



}
package tang.biao;

import java.util.Scanner;

public class AnimalMgr {
	static Animal[] animal = new Animal[3];
	Scanner input=new Scanner(System.in);
	int choose;
	public void init(){
	
		animal[0]= new Cat("加菲猫",4);
		
		animal [1]= new Duck("唐老鸭",2);
		
		animal[2]= new Dolphin("海豚琪琪");
	}
		
	public void showAnimals(){
	     System.out.println("动物名字\t腿的条数\t动物叫");
	     for(Animal animal:animal){
	       String name=animal.getName();
	   int legNum=0;   
	    if(animal instanceof Terrestrial){
	    legNum=((Terrestrial)animal).getlegNum();
	   }
	   String leg=(legNum==0)?"0":(legNum+"");
	   String shout=animal.shout();
	   System.out.println(name+"\t"+leg+"\t"+shout);
	  
	     }
	       System.out.println("是否要继续操作:按0进行修改操作,其它任意数字退出");
	    choose=input.nextInt();
	}
	public void ModifyAnimal() throws Exception {
	String[] names=new String[3];
	int[] nums=new int[3];
	System.out.println("请输入猫的名字:");
	names[0]=input.next();
	System.out.println("请输入猫的腿数:");
	nums[0]=input.nextInt();
	if(nums[0]!=4){
	throw new Exception("猫只有四条腿");

	}
	System.out.println("请输入鸭子的名字:");
	names[1]=input.next();
	System.out.println("请输入鸭子的腿数:");
	nums[1]=input.nextInt();
	if(nums[1]!=2){
	throw new Exception("鸭子只有两条腿");

	}
	System.out.println("请输入海豚的名字:");
	names[2]=input.next();

	animal[0]=new Cat(names[0],nums[0]);
	animal[1]=new Duck(names[1],nums[1]);
	animal[2]=new Dolphin(names[2]);

	 
	}
	}
package tang.biao;

public class TestAnimal {
	public static void main(String[] args) {
		AnimalMgr am = new AnimalMgr();// 获得动物乐园管理的对象
		am.init();// 初始化动物乐园的数据
		// 用循环是否需要修改动物信息
		do {
			am.showAnimals();
			if (am.choose == 0) {
				try { 
					am.ModifyAnimal();
				} catch (Exception ex) {
					ex.printStackTrace();
				}

			}
		} while (am.choose == 0);
		System.out.println("退出程序!!");
	}

}


展开阅读全文

没有更多推荐了,返回首页