電子寵物系統
阿新 • • 發佈:2020-12-30
需求說明
使用封裝實現電子寵物系統的企鵝類正確輸入健康值和親密度
保證健康值的有效性(0-100),否則取預設值60
保證親密度的有效性(0-100),否則取預設值60
使用繼承優化電子寵物系統,抽取父類,建立子類,在子類中使用super呼叫父類構造方法。(選做)
Dog
狗狗類
public class Dog extends Pet{ private int love; @Override public void show() { System.out.println("寵物自白:\n我的名字是"+this.getName()+"健康值是"+'0'+"卿米渡"+this.getLove()+"性別"+getLove()); } public Dog(String name, int sex, int love) { super(name, sex); this.love = love; } public int getLove() { return love; } public void setLove(int love) { if(love>=60&&love<=100){ this.love = love; }else { this.love = 60; } } }
Penguin
企鵝類
public class Penguin extends Pet{ private int health; public Penguin(String name, int sex, int health) { super(name, sex); this.health = health; } public Penguin() { super(); } public int getHealth() { return health; } public void setHealth(int health) { if(health >=60&&health <=100){ this.health = health; }else { this.health = 60; } } }
Pet
父類
public class Pet { private String name; private String sex; public void show(){ } public Pet(String name, int sex) { this.name = name; if (sex==1){ this.sex ="Q仔"; }else { this.sex ="Q妹"; } } public Pet() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
Text
測試類
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("歡迎來到寵物店");
System.out.println("請輸入要領養的寵物的名字");
String name=sc.next();
System.out.println("請輸入要領養的寵物型別1.狗狗 2.企鵝");
int i=sc.nextInt();
if(i==1){
//狗
System.out.println("請輸入狗狗的性別:(1.Q仔 2.Q寶)");
int sex= sc.nextInt();
System.out.println("請輸入狗狗的親密度(1-100之間)");
Dog d = new Dog(name, sex, sc.nextInt());
d.show();
}else {
//企鵝
System.out.println("請輸入企鵝的性別:(1.Q仔 2.Q寶)");
int sex= sc.nextInt();
System.out.println("請輸入企鵝的親密度(1-100之間)");
Penguin p = new Penguin(name, sex, sc.nextInt());
}
}
}