You will write methods of a program that calculates the number of occurrences of a specific type of animal in a list of animal names. For example, in the matrix with animal names as RosieMule TedFish DoodleCat WallyDog JessieDog DanaDog BibsCat MillieCat ElyFish SimonCat CloieFish GoldieFish ZippyFish AlexisDog BuckMule RascalMule GeorgeDog OscarFish GracieMule LuckyDog there are 6 dogs, 4 cats, etc.

Respuesta :

Answer:

In Java:

public static void countAnimal(String [] animalList,String animal) {      

     int count=0;

     for(int i=0; i<animalList.length; i++ ) {

        if(animalList[i].toLowerCase().contains(animal.toLowerCase())) {

           count++;

        }

     }

     System.out.print("There are "+count+" "+animal);

  }

Explanation:

This line defines the method. The method gets a list of animals and a type of animal as its parameters

public static void countAnimal(String [] animalList,String animal) {      

This initializes count to 0

     int count=0;

This iterates through the animal list

     for(int i=0; i<animalList.length; i++ ) {

This checks if the current animal in the list is the type of animal (e.g. dog, cat, etc).

        if(animalList[i].toLowerCase().contains(animal.toLowerCase())) {

If yes, the count variable is incremented by 1

           count++;

        }

     }

This prints the number of animals of that type (e.g. dog, cat, etc).

     System.out.print("There are "+count+" "+animal);

  }

As an additional explanation:

if(animalList[i].toLowerCase().contains(animal.toLowerCase()))

animalList[i].toLowerCase() --> This converts the string of the current animal to lowercase

animal.toLowerCase() --> This converts the animal (e.g. dogs, cats) to lowercase

.contains -> compares if both strings to check if contains the particular animal

See attachment for complete program

Ver imagen MrRoyal