Java中使用封裝實現電子寵物系統的企鵝類正確輸入健康值和親密度
阿新 • • 發佈:2020-12-15
技術標籤:java
.需求說明
使用封裝實現電子寵物系統的企鵝類正確輸入健康值和親密度
保證健康值的有效性(0-100),否則取預設值60
保證親密度的有效性(0-100),否則取預設值60
//企鵝類
public class Pen {
private String name;
private String sex;
private int healthIndex;
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(int sex) { if(sex ==1){ System.out.println("Q仔"); }else{ System.out.println("Q妹"); } } public int getHealthIndex() { return healthIndex; } public void setHealthIndex(int healthIndex) { if (healthIndex > 0 && healthIndex <= 100) { this.healthIndex = healthIndex; } else { System.out.println("健康值應該在0至100之間,,預設值為60"); this.healthIndex = 60; } }
}
//狗狗類
public class Dog {
private String name;
private String sex;
private int intimacy;
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(int sex) { if(sex ==1){ System.out.println("Q仔"); }else{ System.out.println("Q妹"); } } public int getIntimacy() { return intimacy; } public void setIntimacy(int intimacy) { if(intimacy>0&&intimacy<=100){ this.intimacy = intimacy; }else{ System.out.println("親密度應該在0至100之間,,預設值為60"); this.intimacy=60; } }
}
//測試類
import java.util.Scanner;
public class Test1 {
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 num1 = sc.nextInt();
if(num1 == 1){//狗狗
dog.setName(name);
System.out.println(“請輸入狗狗的性別:(1、Q仔,2、Q妹)”);
dog.setSex(sc.nextInt());
System.out.println(“請輸入狗狗的親密度(1~100之間):”);
dog.setIntimacy(sc.nextInt());
System.out.println(“寵物的自白:\n我的名字叫:”+name+“健康值是:”+0+
“,親密度是:”+dog.getIntimacy()+",我的名字是:"+dog.getName());
}else{//企鵝
Pen p = new Pen();
p.setName(name);
System.out.println("請輸入企鵝的性別:(1、Q仔,2、Q妹)");
p.setSex(sc.nextInt());
System.out.println("請輸入企鵝的健康值(1~100之間):");
p.setHealthIndex(sc.nextInt());
System.out.println("寵物的自白:\n我的名字叫:"+name+"健康值是:"+p.getHealthIndex()+
",親密度是:"+0+",我的名字是:"+p.getName());
}
}
}