宠物类:
/** * @author Mr.Wang * 宠物类 * */ public class Animals { private int health;//健康值 private int love;//亲密度 private String name;//名字 private String sex;//性别 public int getHealth() { return health; } public void setHealth(int health) { if(health<0||health>100){ //System.out.println("健康值应该在0至100之间,默认值为60。"); this.health=60; return; } this.health = health; } public int getLove() { return love; } public void setLove(int love) { this.love = love; } 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; } public Animals() {} public Animals(int health, int love, String name,String sex) { if(health<0||health>100){ System.out.println("健康值应该在0至100之间,默认值为60。"); this.health=60; }else { this.health = health; } this.love = 60; this.name = name; this.sex = sex; } //宠物自白 public String toString() { System.out.println("宠物的自白:"); return "我的名字叫"+this.getName()+",我是"+this.getSex()+",健康值是"+this.getHealth()+",初始亲密度为"+this.getLove(); } }
企鹅类:
/** * @author Mr.Wang * 企鹅类 * */ public class Penguin extends Animals{ public Penguin(int health, int love, String name,String sex) { super(health, love, name,sex); } }
狗狗类:
/** * @author Mr.Wang * 狗狗类 * */ public class Dog extends Animals{ public Dog(int health, int love, String name,String sex) { super(health, love, name,sex); } }
测试类:
import java.util.Scanner; public class Text01 { static Scanner input = new Scanner(System.in); public static void main(String[] args) { String sex; int love = 60; System.out.println("欢迎来到宠物商店!"); System.out.println("请输入要领养的宠物的名字:"); String name = input.next(); System.out.print("请选择要领养的宠物类型:(1、狗狗 2、企鹅)"); int choose = input.nextInt(); switch (choose) { case 1: System.out.println("请选择狗狗的性别:(1、雄性 2、雌性)"); int choose1 = input.nextInt(); if(choose1 == 1) { sex = "雄性"; }else { sex = "雌性"; } System.out.println("请输入狗狗的健康值:(0~100)"); int health = input.nextInt(); System.out.println("我的亲密度初始值为60。"); Dog dog = new Dog(health, love, name, sex); String str = dog.toString(); System.out.println(str); break; case 2: System.out.println("请选择企鹅的性别:(1、Q仔 2、Q妹)"); int choose2 = input.nextInt(); if(choose2 == 1) { sex = "Q仔"; }else { sex = "Q妹"; } System.out.println("请输入企鹅的健康值:(0~100)"); int health1 = input.nextInt(); System.out.println("我的亲密度初始值为60。"); Penguin penguin = new Penguin(health1, love, name, sex); String str1 = penguin.toString(); System.out.println(str1); break; default: System.out.println("欢迎使用宠物商店!"); break; } } }
运行结果: