使用集合来存储和管理对象,编写一个Java程序,根据以下要求存储和管理在宠物诊所
注册的一组宠物的数据:
1.该应用程序必须能够处理来自至少两种类型的宠物的数据,如猫和狗。
2.对于每只宠物,它们的名字、年龄、颜色、体重和品种 应该被记录。
提示:考虑创建一个类型为Pet的数组,其中Pet是您创建的一个基类,其中包含名称、年龄
、颜色和权重作为实例变量。每个子类代表每种类型的宠物都有一个额外的实例变量品种,
可以存储特定的宠物品种。例如,它可以是波斯猫,虎斑猫...西班牙猎犬,小猎
犬等等。您需要检查每个变量是否已以您指定的任何格式正确输入。您还需要通知用
户,如果给定宠物的任何数据字段保留为空,该宠物的完整详细信息将不会保存在当前会话
之外。
3.该程序应该包含一个叫做“speak”的方法,它返回一个典型的动物噪声,加上对动物的描述,如:
“喵喵!我是Pixel,一个4岁的虎斑猫
汪汪我是Jack,一只9岁的小猎犬。”
4.该计划需要允许将宠物添加到诊所或从诊所中删除。在创建宠物细节后,不要求有任何设施来
修改宠物细节。
提示:从数组中删除数据可能会在数组中留下一个空白,所以在添加另一只宠物时,计算另
一个宠物总数并搜索下一个免费的数组单元格。
5.必须有可能进行报告。e.打印到屏幕上)在诊所上。该报告应标明可以硬编码的诊所名称、登
记的每种宠物的总数以及这些宠物的主要颜色。
6.该程序应该允许用户查看目前在诊所注册的所有宠物。
7.在一个会议结束时,当项目被终止时,诊所的详细信息以及每个注册宠物的细节应该被写入磁
盘。这些细节应该记录在两个标准文本文件中:一个包含诊所详细信息(称为“诊所细节”。
另一个保存着所有的宠物记录,被称为“宠物细节”。txt" .
提示:不要将空白记录保存到磁盘,在将其内容写入磁盘之前,请检查每个数组单元格中是
否有一个有效的“宠物”对象。如果宠物的详细信息中的任何字段被留空(字符串长度为零
),那么该学生是无效的,他们的详细信息不应该被写入磁盘。
8.当程序启动时,它应该从这些标准文本文件中读取,以便将以前存储的任何数据重新填充应用
程序作为起点。
提示:每个记录都需要创建一个Pet类的新实例,并将其链接到数组中的下一个可用的空闲单
元格。
9.程序用户还必须能够根据名字或颜色搜索宠物,从而显示该宠物的细节,并调用该宠物的语音
()方法。
10.该程序必须只使用一个控制台接口。
您必须开发一组测试用例和至少一个单元测试,并记录将这些测试应用于软件的结果。
其他分配要求:
1.采用面向对象的原则应该在您实现上述需求时很明显,包括使用继承和多态性。
2.一种结构化的测试方法应通过提交一个测试计划来证明,其中包括至少一个符合上述要求的单
元测试和结果。
运行结果(所有功能均已实现,此处仅展示功能3):
部分代码如下:
PetClinicManagement.java
import java.util.List;
import java.util.Scanner;
// Main class for managing a pet clinic
public class PetClinicManagement {
public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
PetClinic petClinic = new PetClinic("Great Pet Clinic"); // Create a new pet clinic instance
petClinic.loadFromFiles(); // Load pet data from files
boolean exit = false;
while (!exit) { // Main menu loop
System.out.println("\n----- Pet Clinic Management -----");
System.out.println("\n------- 1. Add a pet-------------");
System.out.println("\n--------2. Remove a pet----------");
System.out.println("\n--------3. View clinic details---");
System.out.println("\n--------4. View all pets---------");
System.out.println("\n--------5. Search pet by name----");
System.out.println("\n--------6. Search pet by color---");
System.out.println("\n--------7. Save to files and exit");
System.out.print("\n-Please enter your choice (1-7): ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
switch (choice) {
case 1: // Add a pet
System.out.print("Enter pet type (Cat/Dog/Bird): ");
String petType = scanner.nextLine();
System.out.print("Enter pet name: ");
String name = scanner.nextLine();
System.out.print("Enter pet age: ");
while (!scanner.hasNextInt()) { // Validate age input
System.out.println("Error: Please enter a valid age as a number");
System.out.print("Enter pet age: ");
scanner.next(); // Consume invalid input
}
int age = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter pet color: ");
String color = scanner.nextLine();
System.out.print("Enter pet weight: ");
while (!scanner.hasNextDouble()) { // Validate weight input
System.out.println("Error: Please enter a valid weight as a number");
System.out.print("Enter pet weight: ");
scanner.next(); // Consume invalid input
}
double weight = scanner.nextDouble();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter pet breed: ");
String breed = scanner.nextLine();
if (petType.equalsIgnoreCase("Cat")) {
Cat cat = new Cat(name, age, color, weight, breed);
petClinic.addPet(cat); // Add the cat to the pet clinic
System.out.println("Cat added successfully!");
Thread.sleep(1000);
} else if (petType.equalsIgnoreCase("Dog")) {
Dog dog = new Dog(name, age, color, weight, breed);
petClinic.addPet(dog); // Add the dog to the pet clinic
System.out.println("Dog added successfully!");
Thread.sleep(1000);
} else if (petType.equalsIgnoreCase("Bird")) {
Bird bird = new Bird(name, age, color, weight, breed);
petClinic.addPet(bird); // Add the bird to the pet clinic
System.out.println("Bird added successfully!");
Thread.sleep(1000);
} else {
System.out.println("Invalid pet type!");
Thread.sleep(1000);
}
break;
case 2: // Remove a pet
System.out.print("Enter pet name to remove: ");
String petName = scanner.nextLine();
List<Pet> petsToRemove = petClinic.searchPetsByName(petName);
// Check if there are pets found with the given name
if (!petsToRemove.isEmpty()) {
// If multiple pets are found, ask the user to specify which pet to remove
if (petsToRemove.size() > 1) {
System.out.println("Multiple pets found with the name \"" + petName
+ "\". Please specify which pet to remove:");
// Iterate over the list of pets and display their details
for (int i = 0; i < petsToRemove.size(); i++) {
Pet pet = petsToRemove.get(i);
System.out.println((i + 1) + ". Name: " + pet.getName() + ", Type: "
+ pet.getClass().getSimpleName());
// Check the type of the pet and display additional details accordingly
if (pet instanceof Cat) {
System.out.println(" Age: " + pet.getAge() + ", Color: " + pet.getColor()
+ ", Weight: " + pet.getWeight() + ", Breed: " + ((Cat) pet).getBreed());
} else if (pet instanceof Dog) {
System.out.println(" Age: " + pet.getAge() + ", Color: " + pet.getColor()
+ ", Weight: " + pet.getWeight() + ", Breed: " + ((Dog) pet).getBreed());
} else if (pet instanceof Bird) {
System.out.println(
" Age: " + pet.getAge() + ", Color: " + pet.getColor() + ", Weight: "
+ pet.getWeight() + ", Species: " + ((Bird) pet).getBreed());
}
}
System.out.print("Enter the number of the pet to remove: ");
int petIndex = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
if (petIndex >= 1 && petIndex <= petsToRemove.size()) {
Pet pet = petsToRemove.get(petIndex - 1);
petClinic.removePet(pet); // Remove the selected pet from the clinic
System.out.println("Pet \"" + pet.getName() + "\" (Type: "
+ pet.getClass().getSimpleName() + ") removed successfully!");
Thread.sleep(1000);
} else {
System.out.println("Invalid pet number!");
Thread.sleep(1000);
}
} else {
Pet pet = petsToRemove.get(0);
petClinic.removePet(pet); // Remove the pet from the clinic
System.out.println("Pet \"" + pet.getName() + "\" (Type: " + pet.getClass().getSimpleName()
+ ") removed successfully!");
Thread.sleep(1000);
}
} else {
System.out.println("Pet not found!");
Thread.sleep(1000);
}
break;
case 3: // View clinic details
petClinic.printClinicDetails();
Thread.sleep(3000);
break;
case 4: // View all pets
petClinic.printAllPets();
Thread.sleep(3000);
break;
case 5: // Search pet by name
System.out.print("Enter pet name to search: ");
String searchName = scanner.nextLine();
List<Pet> petsByName = petClinic.searchPetsByName(searchName);
if (!petsByName.isEmpty()) {
for (Pet pet : petsByName) {
System.out.println(pet.speak()); // Output the pet's sound
Thread.sleep(2000);
}
} else {
System.out.println("No pets found with the name: " + searchName);
Thread.sleep(1000);
}
break;
case 6: // Search pet by color
System.out.print("Enter pet color to search: ");
String searchColor = scanner.nextLine();
List<Pet> petsByColor = petClinic.searchPetsByColor(searchColor);
if (!petsByColor.isEmpty()) {
for (Pet pet : petsByColor) {
System.out.println(pet.speak()); // Output the pet's sound
Thread.sleep(2000);
}
} else {
System.out.println("No pets found with the color: " + searchColor);
Thread.sleep(1000);
}
break;
case 7: // Save to files and exit
petClinic.saveToFiles(); // Save pet data to files
System.out.println("Data saved successfully!");
System.out.print("Welcome to visit us next time. Goodbye! ~^v^~");
Thread.sleep(1000);
exit = true; // Set exit flag to true, exiting the loop
break;
}
}
scanner.close(); // Close the scanner
}
}
PetClinic.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class PetClinic {
private List<Pet> pets; // List of pets
private String clinicName; // Name of the clinic
// Constructor to initialize the clinic name and the list of pets
public PetClinic(String clinicName) {
this.clinicName = clinicName;
this.pets = new ArrayList<>();
}
public void addPet(Pet pet) { // Add a pet to the list of pets
pets.add(pet);
}
public void removePet(Pet pet) { // Remove a pet from the list of pets
pets.remove(pet);
}
public void printClinicDetails() { // Print the clinic details
System.out.println("Clinic Name: " + clinicName);
System.out.println("Total number of pets: " + pets.size());
System.out.println("Number of cats: " + countPetsByType(Cat.class));
System.out.println("Number of dogs: " + countPetsByType(Dog.class));
System.out.println("Number of birds: " + countPetsByType(Bird.class));
System.out.println("Dominant color: " + getDominantColor());
}
// Count the number of pets by pet type
int countPetsByType(Class<? extends Pet> petClass) {
return (int) pets.stream().filter(petClass::isInstance).count();
}
private List<String> getDominantColor() { // Get the dominant colors
// Use HashMap to store the mapping of colors and their counts
Map<String, Integer> colorCount = new HashMap<>();
for (Pet pet : pets) { // Iterate through the list of pets
// Count the number of each color
colorCount.compute(pet.getColor(), (key, value) -> (value == null) ? 1 : value + 1);
}
int maxCount = colorCount.values().stream().max(Integer::compareTo).orElse(0); // Find the maximum count
List<String> dominantColors = colorCount.entrySet().stream()
// Filter out the colors with counts equal to the maximum count
.filter(entry -> entry.getValue() == maxCount)
.map(Map.Entry::getKey) // Get the colors
.collect(Collectors.toList()); // Collect the results into a list
return dominantColors;
}
public void printAllPets() { // Print the sounds of all pets
pets.forEach(pet -> System.out.println(pet.speak()));
}
public List<Pet> searchPetsByName(String name) { // Search for pets by name
return pets.stream()
.filter(pet -> pet.getName().equalsIgnoreCase(name))
.collect(Collectors.toList());
}
public List<Pet> searchPetsByColor(String color) { // Search for pets by color
return pets.stream()
.filter(pet -> pet.getColor().equalsIgnoreCase(color))
.collect(Collectors.toList());
}
public void saveToFiles() { // Save the clinic and pet details to files
try (BufferedWriter clinicsWriter = new BufferedWriter(new FileWriter("ClinicsDetails.txt"));
BufferedWriter petsWriter = new BufferedWriter(new FileWriter("PetDetails.txt"))) {
clinicsWriter.write("Clinic Name: " + clinicName); // Write the clinic name
clinicsWriter.newLine(); // Write a new line
clinicsWriter.write("Total number of pets: " + pets.size());
clinicsWriter.newLine();
clinicsWriter.write("Number of cats: " + countPetsByType(Cat.class));
clinicsWriter.newLine();
clinicsWriter.write("Number of dogs: " + countPetsByType(Dog.class));
clinicsWriter.newLine();
clinicsWriter.write("Number of birds: " + countPetsByType(Bird.class));
clinicsWriter.newLine();
clinicsWriter.write("Dominant color: " + getDominantColor());
clinicsWriter.newLine();
for (Pet pet : pets) { // Iterate through the list of pets
String petType = pet.getClass().getSimpleName(); // Get the abbreviated type of pet
// Build the detailed information string for the pet
String petData = petType + "|" + pet.getName() + "|" + pet.getAge() + "|" + pet.getColor() + "|"
+ pet.getWeight() + "|" + getSpecificPetData(pet);
petsWriter.write(petData); // Write the pet's detailed information
petsWriter.newLine(); // Write a new line
}
} catch (IOException e) {// Catch IOException
System.out.println("Error writing to files: " + e.getMessage());// Print the error message
}
}
private String getSpecificPetData(Pet pet) { // Get additional data for a specific pet
if (pet instanceof Cat) { // If it's a cat
Cat cat = (Cat) pet;
return cat.getBreed(); // Return the breed of the cat
} else if (pet instanceof Dog) { // If it's a dog
Dog dog = (Dog) pet;
return dog.getBreed(); // Return the breed of the dog
} else if (pet instanceof Bird) { // If it's a bird
Bird bird = (Bird) pet;
return bird.getBreed(); // Return the breed of the bird
}
return "";
}
public void loadFromFiles() { // Load the clinic and pet details from files
try (BufferedReader clinicsReader = new BufferedReader(new FileReader("ClinicsDetails.txt"));
BufferedReader petsReader = new BufferedReader(new FileReader("PetDetails.txt"))) {
String clinicsLine = clinicsReader.readLine(); // Read the first line of clinic details
// If the first line starts with "Clinic Name: "
if (clinicsLine != null && clinicsLine.startsWith("Clinic Name: ")) {
clinicName = clinicsLine.substring(14); // Extract the clinic name
}
String petLine;
while ((petLine = petsReader.readLine()) != null) { // Read the pet details line by line
String[] petData = petLine.split("\\|"); // Split the pet detailed information using "|"
if (petData.length == 6) { // If the length of pet detailed information is 6
String petType = petData[0];
String name = petData[1];
int age = Integer.parseInt(petData[2]);
String color = petData[3];
double weight = Double.parseDouble(petData[4]);
String specificData = petData[5];
// Create a pet object based on the pet type and add it to the pet list
switch (petType) {
case "Cat":
pets.add(new Cat(name, age, color, weight, specificData));
break;
case "Dog":
pets.add(new Dog(name, age, color, weight, specificData));
break;
case "Bird":
pets.add(new Bird(name, age, color, weight, specificData));
break;
}
}
}
} catch (IOException e) {// Catch IOException
System.out.println("Error reading from files: " + e.getMessage());// Print the error message
}
}
}
Pet.java
public class Pet {
private String name; // The name of the pet
private int age; // The age of the pet
private String color; // The color of the pet
private double weight; // The weight of the pet
/**
* Constructor for the Pet class.
*
* @param name The name of the pet.
* @param age The age of the pet.
* @param color The color of the pet.
* @param weight The weight of the pet.
*/
public Pet(String name, int age, String color, double weight) {
this.name = name;
this.age = age;
this.color = color;
this.weight = weight;
}
/**
* Get the name of the pet.
*
* @return The name of the pet.
*/
public String getName() {
return name;
}
/**
* Get the age of the pet.
*
* @return The age of the pet.
*/
public int getAge() {
return age;
}
/**
* Get the color of the pet.
*
* @return The color of the pet.
*/
public String getColor() {
return color;
}
/**
* Get the weight of the pet.
*
* @return The weight of the pet.
*/
public double getWeight() {
return weight;
}
/**
* Make the pet speak.
*
* @return A string representing the pet speaking.
*/
public String speak() {
return "I am a pet";
}
}
测试框架:junit
单元测试:PetClinicTest.java
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class PetClinicTest {
private PetClinic petClinic;
@Before
public void setUp() {
petClinic = new PetClinic("My Clinic");
}
@Test
public void testAddPet() {
// Create pets
Pet pet1 = new Cat("Fluffy", 3, "White", 4.5, "Persian");
Pet pet2 = new Dog("Buddy", 5, "Brown", 8.2, "Labrador");
// Add pets to the clinic
petClinic.addPet(pet1);
petClinic.addPet(pet2);
// Verify the count of pets in the clinic
assertEquals(2, petClinic.countPetsByType(Pet.class));
}
@Test
public void testRemovePet() {
// Create pets
Pet pet1 = new Cat("Fluffy", 3, "White", 4.5, "Persian");
Pet pet2 = new Dog("Buddy", 5, "Brown", 8.2, "Labrador");
// Add pets to the clinic
petClinic.addPet(pet1);
petClinic.addPet(pet2);
// Remove a pet from the clinic
petClinic.removePet(pet1);
// Verify the count of pets in the clinic
assertEquals(1, petClinic.countPetsByType(Pet.class));
}
@Test
public void testSearchPetsByName() {
// Create pets
Pet pet1 = new Cat("Fluffy", 3, "White", 4.5, "Persian");
Pet pet2 = new Dog("Buddy", 5, "Brown", 8.2, "Labrador");
Pet pet3 = new Cat("Whiskers", 2, "Gray", 3.7, "Siamese");
// Add pets to the clinic
petClinic.addPet(pet1);
petClinic.addPet(pet2);
petClinic.addPet(pet3);
// Search for pets by name
List<Pet> result = petClinic.searchPetsByName("Fluffy");
// Verify the search result
assertEquals(1, result.size());
assertEquals("Fluffy", result.get(0).getName());
}
@Test
public void testSearchPetsByColor() {
// Create pets
Pet pet1 = new Cat("Fluffy", 3, "White", 4.5, "Persian");
Pet pet2 = new Dog("Buddy", 5, "Brown", 8.2, "Labrador");
Pet pet3 = new Cat("Whiskers", 2, "Gray", 3.7, "Siamese");
// Add pets to the clinic
petClinic.addPet(pet1);
petClinic.addPet(pet2);
petClinic.addPet(pet3);
// Search for pets by color
List<Pet> result = petClinic.searchPetsByColor("White");
// Verify the search result
assertEquals(1, result.size());
assertEquals("White", result.get(0).getColor());
}
}
测试用例:
import java.util.List;
public class PetClinicManagementTest {
public static void main(String[] args) {
PetClinic petClinic = new PetClinic("Great Pet Clinic");
// Create pets
Cat cat1 = new Cat("Whiskers", 3, "Orange", 5.2, "Siamese");
Dog dog1 = new Dog("Buddy", 5, "Brown", 10.1, "Labrador");
Bird bird1 = new Bird("Tweetie", 2, "Yellow", 0.3, "Canary");
Cat cat2 = new Cat("Whiskers", 4, "White", 4.8, "Persian");
Dog dog2 = new Dog("Max", 2, "Black", 7.6, "German Shepherd");
// Add pets to the clinic
petClinic.addPet(cat1);
petClinic.addPet(dog1);
petClinic.addPet(bird1);
petClinic.addPet(cat2);
petClinic.addPet(dog2);
// Print clinic details
System.out.println("Clinic Details:");
petClinic.printClinicDetails();
// View all pets
System.out.println("\nAll Pets:");
petClinic.printAllPets();
// Search pets by name
System.out.println("\nSearch Pets by Name:");
List<Pet> petsByName = petClinic.searchPetsByName("Whiskers");
if (!petsByName.isEmpty()) {
for (Pet pet : petsByName) {
System.out.println(pet.speak());
}
} else {
System.out.println("No pets found with the name: Whiskers");
}
// Search pets by color
System.out.println("\nSearch Pets by Color:");
List<Pet> petsByColor = petClinic.searchPetsByColor("Brown");
if (!petsByColor.isEmpty()) {
for (Pet pet : petsByColor) {
System.out.println(pet.speak());
}
} else {
System.out.println("No pets found with the color: Brown");
}
// Remove a pet
System.out.println("\nRemove a Pet:");
String petNameToRemove = "Buddy";
List<Pet> petsToRemove = petClinic.searchPetsByName(petNameToRemove);
if (!petsToRemove.isEmpty()) {
Pet petToRemove = petsToRemove.get(0);
petClinic.removePet(petToRemove);
System.out.println("Pet \"" + petToRemove.getName() + "\" removed successfully!");
} else {
System.out.println("Pet not found!");
}
// Print updated clinic details
System.out.println("\nUpdated Clinic Details:");
petClinic.printClinicDetails();
// Save to files
petClinic.saveToFiles();
System.out.println("\nData saved successfully!");
}
}