Common Type of Pet Animal Enum Program Explanation

What is the purpose of the code provided?

The code is designed to ask the user to input a string representing a common type of pet animal and then display the animal's name as an enum using switch-case statements.

What are the common type of pet animal names used in the code?

The common type of pet animal names used are: DOG, CAT, FISH, BIRD, HORSE, and OTHER.

How does the code handle user input for pet animal names?

The code converts the user input to uppercase to make it case-insensitive. If the user input matches one of the predefined animal names, the corresponding enum value is assigned. If the input does not match any of the predefined names, the enum value "OTHER" is assigned.

Code Explanation

Here is the code in Java that implements the functionality described:

```java import java.util.Scanner; public class Main { enum PetAnimal { DOG, CAT, FISH, BIRD, HORSE, OTHER } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a pet animal: "); String input = scanner.nextLine().toUpperCase(); PetAnimal animal; switch (input) { case "DOG": animal = PetAnimal.DOG; break; case "CAT": animal = PetAnimal.CAT; break; case "FISH": animal = PetAnimal.FISH; break; case "BIRD": animal = PetAnimal.BIRD; break; case "HORSE": animal = PetAnimal.HORSE; break; default: animal = PetAnimal.OTHER; break; } System.out.printf("You entered %s.", animal); } } } ```

In this code, we define an enum called PetAnimal with values representing common types of pet animals. We prompt the user to input a pet animal name, convert it to uppercase, and match it using switch-case statements.

If the user input matches one of the animal names, the respective enum value is assigned. Otherwise, the enum value "OTHER" is assigned. The program then prints the entered animal name using printf.

This code ensures that the user input is correctly handled and mapped to the corresponding enum value for pet animal names.

To know more about the code, you can visit the link provided.

← Types of hybrid vehicles Feeder protection size calculation for motors →