Java实现宠物店动物查询
时间: 2023-05-23 14:03:38 浏览: 153
可以使用面向对象编程思想,在宠物类中添加属性(如名字、品种、年龄等)和方法(如喂食、洗澡等),通过定义一个宠物店类,可以在宠物店中添加宠物、查询宠物等功能。具体实现可以参考以下示例代码:
```java
import java.util.ArrayList;
import java.util.List;
// 宠物类
class Pet {
private String name;
private String breed;
private int age;
public Pet(String name, String breed, int age) {
this.name = name;
this.breed = breed;
this.age = age;
}
public void feed() {
System.out.println(name + "正在进食...");
}
public void wash() {
System.out.println(name + "正在洗澡...");
}
// getter and setter methods
}
// 宠物店类
class PetShop {
private List<Pet> pets = new ArrayList<>();
public void addPet(Pet pet) {
pets.add(pet);
}
public List<Pet> getPets() {
return pets;
}
public List<Pet> searchPet(String keyword) {
List<Pet> result = new ArrayList<>();
for (Pet pet : pets) {
if (pet.getName().contains(keyword) || pet.getBreed().contains(keyword)) {
result.add(pet);
}
}
return result;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Pet pet1 = new Pet("小白", "猫", 2);
Pet pet2 = new Pet("小黑", "狗", 1);
Pet pet3 = new Pet("小花", "猫", 3);
PetShop petShop = new PetShop();
petShop.addPet(pet1);
petShop.addPet(pet2);
petShop.addPet(pet3);
List<Pet> result = petShop.searchPet("猫");
for (Pet pet : result) {
System.out.println(pet.getName() + " " + pet.getBreed() + " " + pet.getAge());
}
}
}
```
运行结果:
```
小白 猫 2
小花 猫 3
```
阅读全文