可以使用 Java 实现领养宠物的程序。可以创建一个主菜单类,在该类中使用 switch 语句根据用户的选择返回相应的宠物。
实现细节如下:
定义一个枚举类型PetType,用于表示宠物类型,如狗、猫等。定义一个Pet类,用于表示宠物,包含宠物类型和名称等属性。定义一个PetStore类,用于存储宠物,并提供领养宠物的方法。定义一个MainMenu类,用于显示主菜单,并根据用户的选择调用PetStore类的领养宠物的方法返回相应的宠物。示例代码:
```java enum PetType { DOG, CAT, BIRD }
class Pet { private PetType type; private String name;
public Pet(PetType type, String name) {
this.type = type;
this.name = name;
}
public PetType getType() {
return type;
}
public String getName() {
return name;
}
12345678910111213}
class PetStore { private List pets;
public PetStore() {
pets = new ArrayList<Pet>();
pets.add(new Pet(PetType.DOG, "旺财"));
pets.add(new Pet(PetType.CAT, "喵喵"));
pets.add(new Pet(PetType.BIRD, "鸟鸟"));
}
public Pet adoptPet(PetType type) {
for (Pet pet : pets) {
if (pet.getType() == type) {
pets.remove(pet);
return pet;
}
}
return null;
}
1234567891011121314151617}
class MainMenu { private PetStore petStore;
public MainMenu() {
petStore = new PetStore();
}
public void show() {
System.out.println("欢迎光临宠物商店");
System.out.println("1. 领养狗狗
12345678