Post

Created by @nathanedwards
 at November 3rd 2023, 2:50:25 pm.

AP Computer Science Exam Question

You are tasked with writing a program that determines the type of animal based on its characteristics. The program should take in an integer legs representing the number of legs the animal has, and a boolean hasFur representing whether the animal has fur or not. Based on these inputs, the program should determine and display the type of animal. Use the following classifications:

  • If the animal has 2 legs and has fur, it is a dog.
  • If the animal has 4 legs and has fur, it is a cat.
  • If the animal has 4 legs and does not have fur, it is a lizard.
  • If the animal has 0 legs, it is a snake.
  • For any other input values, display "Unknown animal".

Write a Java program to solve the problem. Use control flow statements (if-else statements) to handle different cases.

Important Note: Make sure to use the provided variable names and follow the expected program behavior as mentioned above.

public class AnimalType {
    public static void main(String[] args) {
        int legs = 4;
        boolean hasFur = true;
        
        // Determine animal type based on inputs
        String animalType;
        if (legs == 2 && hasFur) {
            animalType = "dog";
        } else if (legs == 4 && hasFur) {
            animalType = "cat";
        } else if (legs == 4 && !hasFur) {
            animalType = "lizard";
        } else if (legs == 0) {
            animalType = "snake";
        } else {
            animalType = "Unknown animal";
        }
        
        // Display the animal type
        System.out.println("The animal is a " + animalType + ".");
    }
}

Explanation

  1. We start by initializing the legs variable with a value of 4 and hasFur variable with a value of true, as mentioned in the problem statement.

  2. We define a variable animalType as a string to store the determined animal type based on the inputs.

  3. Using if-else statements, we compare the input values with the given conditions to determine the animal type.

  4. The first condition checks if the animal has 2 legs and has fur. If both conditions are true, we assign the animal type as "dog".

  5. The second condition checks if the animal has 4 legs and has fur. If both conditions are true, we assign the animal type as "cat".

  6. The third condition checks if the animal has 4 legs and does not have fur. If both conditions are true, we assign the animal type as "lizard".

  7. The fourth condition checks if the animal has 0 legs. If true, we assign the animal type as "snake".

  8. If none of the above conditions are true, we assign the animal type as "Unknown animal".

  9. Finally, we display the determined animal type using the System.out.println statement.

In this scenario, the output would be:

The animal is a cat.

Note: The output can vary depending on the initial values assigned to legs and hasFur variables.