2.4 Zoo Learning Activity

Zoo 2.4 — Lists and Loops

The zoo would like to be able to have more animals. In this assignment, you will define a list of animals, add multiple animals to it, and use loops to work with the animals in the list. The existing pen and tank arrays will continue to describe their display spaces.

1.Getting Started
A Copy your Zoo 2.3 ending code, renaming both the folder and the Visual Studio solution file for Zoo 2.4 using your last name. Open the copied solution and restore its NuGet packages.
B In MainWindow.xaml, change only the window Title to identify Zoo 2.4 and your last name. Keep the project target at .NET Framework 4.8.
Current Zoo 2.3 classes involved in population, display areas and births, before any 2.4 changes.
Starting structure — current Zoo 2.3
  • New
  • Changed
  • Removed
C Check Your Work
1 Select Build > Build Solution. Open View > Error List and resolve any errors introduced by this task.
2 Start the copied project and create both zoos. Confirm Como’s pen has Dolly in its second space and San Diego’s tank has Patti at row 1, column 1.
3 Click a direction button for each zoo and confirm its map refreshes without moving the other zoo’s animal.
Keep a Population List
Acceptance Criteria
  • Como Zoo starts with Dolly, Dixie and Pammy; San Diego Zoo starts with Patti and Harold.
  • The animals shown in the display arrays are the same objects held by the population list.
2.Define a list for the zoo that will hold animals
Problem

Currently, the zoo has one featured animal that can be acted upon. The zoo would like to be able to have more animals.

Solution

You will define a list of animals and add the featured animal to it.

A In the Zoo and MainWindow classes, add the fields shown in the class diagram below. The methods shown are introduced in later tasks.
Zoo gains an Animal list and five population methods; MainWindow gains population result fields; Animal.Move changes.
New population members and the changed Move method
  • New
  • Changed
  • Removed
1 In Zoo.cs, add using System.Collections.Generic; alongside the existing using directives so List<Animal> can be used.
2 In the Zoo class, define a public field of type List<Animal> named Animals. Instantiate the list using field initializer syntax.
Instantiate the population list
public List<Animal> Animals = new List<Animal>();
3 In the MainWindow class, define ZooAnimalCount as int and ZooAverageAnimalWeight as double.
B Check Your Work
1 Select Build > Build Solution. Open View > Error List and resolve any errors introduced by this task.
2 Read the Zoo.Animals declaration. Confirm it creates a List<Animal> for each Zoo instance.
3 Trace creation before any registration call: this.Animals is not null and this.Animals.Count is 0.
3.Add animals to the Como Zoo list — CreateComoZoo()
Problem

The zoo has a list now but no animals have been added to it.

Solution

You will instantiate multiple animals and add them to the zoo’s list of animals.

A In CreateComoZoo in MainWindow.xaml.cs, replace the existing block from this.ComoZoo.FeaturedAnimal = new Animal() through the BirthArea.Mother assignment with the following code. Keep the existing zoo, service, visitor and restroom setup before this block.
Create and register Dolly
Animal animal = new Animal();
animal.Sex = "Female";
animal.Name = "Dolly";
animal.Age = 4;
animal.Weight = 35.3;
animal.HappinessLevel = 0;
animal.Type = "Dingo";
animal.MakePregnant();
this.ComoZoo.BirthArea.Mother = animal;
this.ComoZoo.Animals.Add(animal);
1 In the existing pen setup, use animal instead of ComoZoo.FeaturedAnimal when assigning Pen.Animal. Keep the existing array, starting position, PlaceAnimal and DisplayAnimalArea calls.
B In CreateComoZoo, after the existing pen placement and display calls, instantiate another Animal using the previously defined animal variable. Assign its fields, call MakePregnant, and add it to Animals. Repeat for both animals in the table.
Additional Como animals
Name Type Sex Age Weight Call MakePregnant
Dixie Dingo Female 3 33.8 Yes
Pammy Platypus Female 2 15.5 Yes
CreateComoZoo keeps the existing setup and display arrays, adds the first animal, then reuses the local variable to add the remaining population.
CreateComoZoo — register each animal reference
  • New
  • Changed
  • Removed
C Check Your Work
1 Select Build > Build Solution. Open View > Error List and resolve any errors introduced by this task.
2 In MainWindow.xaml.cs, set a breakpoint on the closing brace of CreateComoZoo by clicking its left margin.
3 Press F5 to start or continue the application. Click New Como Zoo.
4 When Visual Studio pauses, open Debug > Windows > Watch > Watch 1. Enter each full expression below in a separate Watch row.
5 Confirm this.ComoZoo.Animals.Count is 3.
6 Confirm this.ComoZoo.Animals[0].Name is "Dolly".
7 Confirm this.ComoZoo.Animals[1].Name is "Dixie".
8 Confirm this.ComoZoo.Animals[2].Name is "Pammy".
9 Confirm this.ComoZoo.Pen.PenSpaces[1] refers to Dolly.
10 Continue and confirm only one map space is occupied. The population list includes animals that have not been assigned display spaces.
11 Press F5 to continue. Stop debugging and remove the breakpoint before the next check.
4.Add animals to the San Diego Zoo list — CreateSanDiegoZoo()
A In CreateSanDiegoZoo, replace Patti’s FeaturedAnimal creation and field assignments with a local Animal variable named animal, using the same pattern as Dolly. Declare animal once in this method; CreateComoZoo’s local variable is not available here. Keep the existing service and tank setup.
CreateSanDiegoZoo keeps the existing setup and display arrays, adds the first animal, then reuses the local variable to add the remaining population.
CreateSanDiegoZoo — register Patti and Harold
  • New
  • Changed
  • Removed
San Diego animals
Name Type Sex Age Weight HappinessLevel Call MakePregnant
Patti Platypus Female 5 3.27 0 Yes
Harold Hummingbird Male 1 0.5 0 by default No
1 Replace the FeaturedAnimal creation and field assignments with the local animal reference, using Patti’s existing values. Keep BirthArea.Mother connected to Patti and add Patti to Animals.
2 Assign the same animal reference to Tank.Animal and keep the current tank placement and display calls.
3 After the display call, assign a new Animal to animal, use Harold’s table values and add Harold to Animals.
B Check Your Work
1 Select Build > Build Solution. Open View > Error List and resolve any errors introduced by this task.
2 In MainWindow.xaml.cs, set a breakpoint on the closing brace of CreateSanDiegoZoo by clicking its left margin.
3 Press F5 to start or continue the application. Click New San Diego Zoo.
4 When Visual Studio pauses, open Debug > Windows > Watch > Watch 1. Enter each full expression below in a separate Watch row.
5 Confirm this.SanDiegoZoo.Animals.Count is 2.
6 Confirm this.SanDiegoZoo.Animals[0].Name is "Patti".
7 Confirm this.SanDiegoZoo.Animals[1].Name is "Harold".
8 Confirm this.SanDiegoZoo.Tank.TankSpaces[1, 1] refers to Patti.
9 Continue and confirm only one map space is occupied. The population list includes animals that have not been assigned display spaces.
10 Press F5 to continue. Stop debugging and remove the breakpoint before the next check.
After Como creation, list item zero, the pen animal, pen space one and birthing-room mother refer to the same Dolly; Dixie and Pammy are separate list items.
One Dolly object, several references
  • New
  • Changed
  • Removed
Review and Wake All Animals
Acceptance Criteria
  • The population count uses the list Count.
  • Weight calculations and wake-all actions include every listed animal.
5.Update Animal.Move()
A In the Animal class, modify the Move method based on the activity diagram below.
Animal.Move calculates one percent of the current weight and subtracts it.
Move — reduce the current animal’s weight by one percent
  • New
  • Changed
  • Removed
1 In the method body, define a variable of type double named weightLossAmount and assign it one percent of the current instance’s Weight.
2 Subtract weightLossAmount from the current instance’s Weight.
B Check Your Work
1 Open Animal.Move() in the source. Follow its statements from top to bottom using the sample values below; this is a paper/source trace, so do not run or edit the application for this check.
2 Use Dolly’s this.Weight of 35.3. Confirm weightLossAmount is approximately 0.353.
3 Subtract once and confirm this.Weight is approximately 34.947.
6.Wake the Zoo Animals — WakeAllAnimals()
Problem

The employees of the zoo would like a way to wake up all the animals in the zoo.

Solution

You will write a method that loops through the list of Animals and calls each animal’s Move method.

A In the Zoo class, define the WakeAllAnimals method based on the class diagram. Use the activity diagram below to write its body with a foreach loop.
WakeAllAnimals visits every Animal reference in the list and calls Move once.
WakeAllAnimals — call Move once per listed animal
  • New
  • Changed
  • Removed
1 Use an Animal variable named animal for the current list item.
2 Call that animal’s Move method inside the foreach loop.
B Check Your Work
1 Open Zoo.WakeAllAnimals() in the source. Follow its statements from top to bottom using the sample values below; this is a paper/source trace, so do not run or edit the application for this check.
2 Use Como’s starting list: this.Animals[0].Name is Dolly, this.Animals[1].Name is Dixie and this.Animals[2].Name is Pammy.
3 Follow the foreach loop. Confirm each of those three references receives exactly one Move() call.
4 Confirm the loop stops after the third item. No runtime button is needed for this source trace.
7.Get the total animal weight — CalculateTotalAnimalWeight()
Problem

Now that the zoo has a list of animals, they would like to get some information based on the animals.

Solution

You will add methods that determine the total and average weight of the animals in the zoo.

A In the Zoo class, define a method named CalculateTotalAnimalWeight with a return type of double. Use the activity diagram below to write its body.
The total starts at zero and adds each listed animal weight once, then is returned.
CalculateTotalAnimalWeight — accumulate and return the total
  • New
  • Changed
  • Removed
1 In the method body, define an accumulator variable of type double named totalWeight and assign it zero.
2 Define a foreach loop that adds each animal’s Weight to totalWeight. Return totalWeight after the loop.
B Check Your Work
1 Open Zoo.CalculateTotalAnimalWeight() in the source. Follow its statements from top to bottom using the sample values below; this is a paper/source trace, so do not run or edit the application for this check.
2 Start totalWeight at 0.0. Use Como’s animal weights 35.3, 33.8 and 15.5.
3 After each iteration, confirm totalWeight is approximately 35.3, then 69.1, then 84.6.
4 Trace an empty this.Animals list. Confirm the loop body does not execute and the method returns 0.0.
8.Get the average animal weight — CalculateAverageAnimalWeight()
A In the Zoo class, define a method named CalculateAverageAnimalWeight with a return type of double. Use the activity diagram below, including its check for an empty list.
An empty population returns zero; otherwise the total weight is divided by the list Count.
CalculateAverageAnimalWeight — handle the empty-list path
  • New
  • Changed
  • Removed
1 Declare averageWeight as double and initialize it to zero. Use Animals.Count to decide whether division is possible.
2 If the list is not empty, assign averageWeight to the return of CalculateTotalAnimalWeight divided by Animals.Count. Return averageWeight.
B Check Your Work
1 Open Zoo.CalculateAverageAnimalWeight() in the source. Follow its statements from top to bottom using the sample values below; this is a paper/source trace, so do not run or edit the application for this check.
2 With Como’s starting list, confirm this.Animals.Count is 3 and the total weight is approximately 84.6. Confirm the returned average is approximately 28.2.
3 With San Diego’s starting list, confirm count 2, total approximately 3.77 and average approximately 1.885.
4 Trace an empty list. Confirm the method returns 0.0 before attempting division by the count.
Provide Population Controls for Each Zoo
Acceptance Criteria
  • Each zoo has wake, count and average-weight buttons.
  • Each new handler checks that its zoo exists and displays its own result.
9.Add the six population buttons
A In MainWindow.xaml, add these complete elements directly after newComoZooButton inside comoZooStackPanel.
Como population buttons
<Button x:Name="comoZooWakeAllAnimals" Content="Wake all animals" Click="comoZooWakeAllAnimals_Click"/>
<Button x:Name="getComoZooAnimalCount" Content="Get animal count" Click="getComoZooAnimalCount_Click"/>
<Button x:Name="getComoZooAverageAnimalWeight" Content="Get average animal weight" Click="getComoZooAverageAnimalWeight_Click"/>
B Add these complete elements directly after newSanDiegoZooButton inside sanDiegoZooStackPanel.
San Diego population buttons
<Button x:Name="sanDiegoZooWakeAllAnimals" Content="Wake all animals" Click="sanDiegoZooWakeAllAnimals_Click"/>
<Button x:Name="getSanDiegoZooAnimalCount" Content="Get animal count" Click="getSanDiegoZooAnimalCount_Click"/>
<Button x:Name="getSanDiegoZooAverageAnimalWeight" Content="Get average animal weight" Click="getSanDiegoZooAverageAnimalWeight_Click"/>
C Create the six Click handlers in MainWindow.xaml.cs with the exact names shown in the XAML. Use the next task to complete their bodies before building.
10.Complete the population button handlers
A Replace each of the three empty Como handlers, including its signature and braces, with the matching complete example below. The activity diagrams show their control flow.
Wake-all handler
private void comoZooWakeAllAnimals_Click(object sender, RoutedEventArgs e)
{
    if (this.ComoZoo == null)
    {
        this.DisplayMessage("Create Como Zoo first.");
        return;
    }

    this.ComoZoo.WakeAllAnimals();
    this.DisplayMessage("All animals were moved.");
}
The Como WakeButton handler checks that the zoo exists, performs its population action and displays the result.
Wake-all handler — action and result
  • New
  • Changed
  • Removed
Count handler
private void getComoZooAnimalCount_Click(object sender, RoutedEventArgs e)
{
    if (this.ComoZoo == null)
    {
        this.DisplayMessage("Create Como Zoo first.");
        return;
    }

    this.ZooAnimalCount = this.ComoZoo.Animals.Count;
    this.DisplayMessage("Animal count: " + this.ZooAnimalCount);
}
The Como CountButton handler checks that the zoo exists, performs its population action and displays the result.
Count handler — action and result
  • New
  • Changed
  • Removed
Average-weight handler
private void getComoZooAverageAnimalWeight_Click(object sender, RoutedEventArgs e)
{
    if (this.ComoZoo == null)
    {
        this.DisplayMessage("Create Como Zoo first.");
        return;
    }

    this.ZooAverageAnimalWeight = this.ComoZoo.CalculateAverageAnimalWeight();
    this.DisplayMessage("Average animal weight: " + this.ZooAverageAnimalWeight);
}
The Como AverageButton handler checks that the zoo exists, performs its population action and displays the result.
Average-weight handler — action and result
  • New
  • Changed
  • Removed
B Complete the three San Diego handlers using the matching Como example. Use the replacements in this table; keep the shared MainWindow result fields unchanged.
Remaining handler setup
San Diego handler Use this Como example Zoo reference Create-first message
sanDiegoZooWakeAllAnimals_Click comoZooWakeAllAnimals_Click this.SanDiegoZoo Create San Diego Zoo first.
getSanDiegoZooAnimalCount_Click getComoZooAnimalCount_Click this.SanDiegoZoo Create San Diego Zoo first.
getSanDiegoZooAverageAnimalWeight_Click getComoZooAverageAnimalWeight_Click this.SanDiegoZoo Create San Diego Zoo first.
C Check Your Work
1 Select Build > Build Solution. Open View > Error List and resolve any errors introduced by this task.
2 Restart the application without creating either zoo.
3 Click Como’s wake, count and average buttons separately. Confirm each displays Create Como Zoo first..
4 Click San Diego’s wake, count and average buttons separately. Confirm each displays Create San Diego Zoo first..
5 Confirm no click causes a null-reference exception.
Find the Animal Needed for Care
Acceptance Criteria
  • A type search returns the first match or null.
  • A pregnant-animal search also checks pregnancy before choosing a mother.
11.Feed a particular animal in the zoo — FindAnimal(string type)
Problem

The feeding sequence still uses FeaturedAnimal. Additionally, there is currently no way for that sequence to find a particular type of animal in the zoo’s list.

Solution

You will set up a loop that finds a particular animal and uses it in the feeding sequence.

A In the Zoo class, define FindAnimal with a return type of Animal and a parameter of type string named type. Follow the activity diagram below.
FindAnimal starts with no result, stops at the first matching animal and returns null if the search has no match.
FindAnimal — first match or null
  • New
  • Changed
  • Removed
1 In the method body, define an Animal variable named foundAnimal and assign it null. Define a foreach loop that loops through Animals.
2 Check whether the current animal’s Type is the same as type. For a match, store the current animal reference in foundAnimal and break out of the loop. Return foundAnimal after the loop.
B Check Your Work
1 Open Zoo.FindAnimal("Dingo") in the source. Follow its statements from top to bottom using the sample values below; this is a paper/source trace, so do not run or edit the application for this check.
2 Use Como’s starting list. Confirm foundAnimal begins as null.
3 Compare this.Animals[0].Type with Dingo. Confirm Dolly matches, foundAnimal receives her reference and break stops before Dixie.
4 Trace a separate search for Hummingbird. Confirm none of the three Type values match and the method returns null.
12.Update MainWindow.FeedAnimal(...)
A In MainWindow.xaml.cs, change the animal argument passed into the existing Visitor.FeedAnimal call. Use the search result from zoo.FindAnimal(animalName). Keep the shared helper’s signature, zoo-null check, result-code switch and messages.
MainWindow.FeedAnimal searches the zoo by type and passes that returned reference into the existing purchase and feeding flow.
Changed feeding helper — search before the existing feeding action
  • New
  • Changed
  • Removed
A feeding button enters MainWindow.FeedAnimal, Zoo.FindAnimal returns the first type match, Guest.FeedAnimal returns its result code and MainWindow displays the existing message.
The animal reference travels from Zoo.FindAnimal into Guest.FeedAnimal
  • New
  • Changed
  • Removed
B In the two existing feeding handlers, replace only the shared FeedAnimal call with the corresponding statement from this table.
Existing feeding calls
Handler Complete replacement statement
darlaFeedDingoButton_Click this.FeedAnimal(this.ComoZoo, "Como Zoo", "Dingo", "Darla");
daveFeedPlatypusButton_Click this.FeedAnimal(this.SanDiegoZoo, "San Diego Zoo", "Platypus", "Dave");
C Check Your Work
1 Select Build > Build Solution. Open View > Error List and resolve any errors introduced by this task.
2 Set a breakpoint on the return statement in Zoo.FindAnimal.
3 Click New Como Zoo to reset that zoo. Do not feed, refill, move or give birth before this test.
4 Click Darla, feed dingo. Confirm returned foundAnimal.Name is Dolly.
5 Follow the return to MainWindow.FeedAnimal. Confirm the same reference is passed to Guest.FeedAnimal. Continue and confirm feeding succeeds.
6 Click New San Diego Zoo to reset that zoo. Do not feed, refill, move or give birth before this test.
7 Click Dave, feed platypus. Confirm the search returns Patti and the completed feeding reports success.
8 Press F5 to continue. Stop debugging and remove the breakpoint before the next check.
13.Birth a particular animal in the zoo — FindPregnantAnimal(string type)
Problem

Currently the birthing of an animal is only happening to the featured animal, but now that there are multiple animals that are pregnant the zoo needs the capability to find the particular animal that needs to give birth.

Solution

You will use a foreach loop to find a pregnant animal and refactor the BirthAnimal method to handle that particular animal.

A In the Zoo class, define FindPregnantAnimal with a return type of Animal and a parameter of type string named type. Use the activity diagram below.
FindPregnantAnimal starts with no result, stops at the first matching animal and returns null if the search has no match.
FindPregnantAnimal — filter by type and pregnancy
  • New
  • Changed
  • Removed
1 In the method body, define an Animal variable named foundAnimal and assign it null. Define a foreach loop that loops through Animals.
2 Check whether the current animal’s Type matches type and the current animal is pregnant. Store the first matching animal reference in foundAnimal and break out of the loop. Return foundAnimal after the loop.
B Check Your Work
1 Open Zoo.FindPregnantAnimal("Dingo") in the source. Follow its statements from top to bottom using the sample values below; this is a paper/source trace, so do not run or edit the application for this check.
2 For a fresh Como list, confirm this.Animals[0].Name is Dolly and her pregnancy test is true. Confirm Dolly is returned.
3 Trace a separate hypothetical case where Dolly is no longer pregnant and Dixie still is. Confirm Dolly is skipped and this.Animals[1] is returned.
Include Newborns in the Population
Acceptance Criteria
  • A successful birth adds the returned baby reference once.
  • Existing display placement and occupied-space protection continue to work.
14.Refactor the BirthAnimal method
A In Zoo.cs, keep the existing BirthAnimal(Animal mother) signature and replace its body using the activity diagram below. The mother parameter already exists in this version.
Zoo.BirthAnimal asks the room to deliver a baby and adds a non-null returned baby to the population.
BirthAnimal — register only a delivered baby
  • New
  • Changed
  • Removed
1 Call this.BirthArea.BirthAnimal(mother) and store the returned reference in a local Animal variable named baby.
2 Add baby to Animals only when it is not null. Return baby after that check so both the success and no-birth paths return a result.
B Check Your Work
1 Open Zoo.BirthAnimal in the source. Follow its statements from top to bottom using the sample values below; this is a paper/source trace, so do not run or edit the application for this check.
2 Follow a non-null baby returned from this.BirthArea.BirthAnimal(mother). Confirm this.Animals.Add(baby) runs once and the method returns that same reference.
3 Trace a separate call returning null. Confirm the Add call is skipped and this.Animals.Count stays unchanged.
4 Confirm the registration path does not use new Animal() to replace the returned baby.
15.Connect the existing birth handlers to the pregnant-animal search
A In MainWindow.xaml.cs, replace each existing baby-assignment statement with the corresponding statement below. Keep the rest of each handler, including the occupied-space guard, baby name, array placement, map refresh, temperature update and messages.
Existing birth-handler assignments
Handler Complete replacement statement
birthDingoButton_Click Animal baby = this.ComoZoo.BirthAnimal(this.ComoZoo.FindPregnantAnimal("Dingo"));
birthPlatypusButton_Click Animal baby = this.SanDiegoZoo.BirthAnimal(this.SanDiegoZoo.FindPregnantAnimal("Platypus"));
The existing empty-space guard runs before searching. A successful birth adds one baby reference to the population, then the handler places that same baby in the display array.
Search, birth, population registration and existing array placement
  • New
  • Changed
  • Removed
B Check Your Work
1 Set a breakpoint on the closing brace of birthDingoButton_Click.
2 Click New Como Zoo to reset that zoo. Do not feed, refill, move or give birth before this test.
3 Click Give birth to dingo once. Do not feed, wake or move first. At the breakpoint open Watch.
4 Confirm this.ComoZoo.Animals.Count is 4.
5 Confirm this.ComoZoo.Pen.PenSpaces[0].Name is "Baby".
6 Confirm this.ComoZoo.Pen.PenSpaces[1].Name is "Dolly".
7 Confirm this.ComoZoo.Animals[3] and this.ComoZoo.Pen.PenSpaces[0] contain the same newborn reference.
8 Continue. Confirm two occupied map spaces and an area count of 2.
9 Click Give birth to dingo again. Confirm the occupied-space message appears. Continue past the breakpoint if reached, then click the population-count button: confirm 4.
10 Press F5 to continue. Stop debugging and remove the breakpoint before the next check.
After the first successful Como birth, the list has four animals while the pen has two occupants; the list and pen both refer to the same newborn.
The same newborn is registered in the list and displayed in the pen
  • New
  • Changed
  • Removed
16.Remove the obsolete Zoo.FeaturedAnimal field
A After the creation, feeding and birth changes are complete, remove the FeaturedAnimal field from Zoo.cs. Keep Pen.Animal, Tank.Animal and BirthArea.Mother; these references still have different jobs.
The changed creation and feeding methods use the list; Zoo.FeaturedAnimal is removed after callers are updated.
Changed methods and the removed Zoo field
  • New
  • Changed
  • Removed
B Check Your Work
1 Open Zoo.cs. Confirm the FeaturedAnimal field declaration has been removed.
2 Select Build > Build Solution. Open View > Error List and resolve any errors introduced by this task.
3 If the Error List reports a FeaturedAnimal reference, open that caller and compare it with this page’s creation, feeding or birth update.
4 Confirm Pen.Animal, Tank.Animal and BirthArea.Mother remain; these still identify animals used by the display and birth workflows.
Check the completed zoo population features
17.Check the population controls and existing display behavior together
A Remove breakpoints from earlier checks. Build and start the application, create both zoos, then use each zoo’s count and average buttons before feeding, waking or birthing an animal. Compare the displayed values with this table.
Fresh population results
Zoo List count Total used by the average Average Displayed-area occupants
Como Zoo 3 Approximately 84.6 Approximately 28.2 1
San Diego Zoo 2 Approximately 3.77 Approximately 1.885 1
B Set a breakpoint at the end of WakeAllAnimals, click Como’s Wake all animals once, and inspect the weights. Use the following values only after recreating Como and before any feeding or births.
After one fresh Como wake action
Animal Watch expression inside Zoo.WakeAllAnimals Approximate Weight
Dolly this.Animals[0].Weight 34.947
Dixie this.Animals[1].Weight 33.462
Pammy this.Animals[2].Weight 15.345
1 Press F5 to continue, then use Como’s Get animal count button. Confirm the pen map and population count stay the same. Animal.Move changes weight; it does not assign a new array location.
2 Use San Diego’s count and average buttons. Confirm their results are unchanged by waking Como.
C Recreate San Diego Zoo. With the breakpoint still at the end of WakeAllAnimals, click San Diego’s Wake all animals button once.
1 While paused inside Zoo.WakeAllAnimals, inspect this.Animals[0].Weight as approximately 3.2373 for Patti and this.Animals[1].Weight as approximately 0.495 for Harold.
2 Press F5 to continue, then remove the WakeAllAnimals breakpoint before the remaining checks.
D Temporarily change only the "Dingo" argument in darlaFeedDingoButton_Click to "Digno". Build, recreate Como and click Darla, feed dingo. Confirm the existing no-animal message appears; FindAnimal returns null.
1 Restore "Dingo", build and start the application, then create Como again. Confirm feeding succeeds before continuing.
18.Follow list references as the local variable is reused
A Remove earlier breakpoints. In CreateComoZoo, set a breakpoint on Animal animal = new Animal(). With the application running, click New Como Zoo. The highlighted statement has not executed yet.
Watch before the first Animal statement
Expression Expected state
this.ComoZoo.Animals An existing empty list; this.ComoZoo.Animals.Count is 0
animal Not assigned yet; the debugger may show null or unavailable at this point
this.ComoZoo.Pen null; the pen has not been created yet
this.ComoZoo.BirthArea.Mother null; Dolly has not been assigned yet
B Use F10 to follow creation and registration; expand objects in Watch as you step.
1 After creating Dolly, step through her assignments and MakePregnant. Before Animals.Add executes, its Count is still 0; after that statement executes, Count is 1.
2 After the pen has been created and placed, observe that its Animal, PenSpaces[1], the list’s first item and BirthArea.Mother refer to Dolly.
3 Step over the next animal = new Animal() statement. The local now refers to a different object, but the list’s first item and Pen.Animal still refer to Dolly.
4 Continue through Dixie and Pammy registration. Observe Count change to 2 and then 3.
C Check Your Work
1 At the pause from the preceding walkthrough, expand this.ComoZoo.Animals[0] in Watch. Confirm its Name is still Dolly.
2 Compare it with the local animal variable after that variable has been assigned a different new Animal(). Confirm the local now refers to the later animal while list index 0 still refers to Dolly.
3 Read the Add call: the list stored the earlier reference, not a permanent link to the local variable.
4 Press F5 to continue. Stop debugging and remove the breakpoint before the next check.
19.Step into a list search and follow the returned reference
A Remove the creation breakpoint and recreate Como. In MainWindow.FeedAnimal, set a breakpoint on the feedResult assignment that contains zoo.FindAnimal(animalName). Click Darla, feed dingo.
Watch at the shared feeding helper
Expression Expected state before stepping into FindAnimal
zoo.Name "Como Zoo"
animalName "Dingo"
zoo.Animals zoo.Animals.Count is 3
type Unavailable in this method; it is the next method’s parameter
foundAnimal Unavailable in this method
animal Unavailable in this method; a foreach variable belongs to FindAnimal
this.Animals Unavailable here because this refers to MainWindow
B Use F11 to enter Zoo.FindAnimal, then F10 to follow its loop.
1 On entry, this refers to the Zoo and type is "Dingo". After the declaration executes, foundAnimal is null.
2 When the first list item is selected by foreach, animal refers to Dolly. After the matching branch executes, foundAnimal also refers to Dolly.
3 Observe the break leave the loop and the return pass Dolly back to the feeding expression. Use F11 to enter Guest.FeedAnimal and confirm its animal parameter refers to Dolly. This parameter and the earlier foreach variable share the name animal but belong to different methods.
C Check Your Work
1 At the preceding search breakpoint, inspect foundAnimal.Name and confirm Dolly.
2 Step out to MainWindow.FeedAnimal. Confirm the search result becomes the animal argument to Guest.FeedAnimal.
3 Continue. Confirm the success message appears after the search, purchase and feeding calls have returned.
4 Press F5 to continue. Stop debugging and remove the breakpoint before the next check.
20.Watch the total become the average
A Remove the feeding breakpoint and recreate San Diego Zoo. Set a breakpoint on the ZooAverageAnimalWeight assignment in getSanDiegoZooAverageAnimalWeight_Click and click Get average animal weight.
Watch at the average button
Expression Expected state
this.SanDiegoZoo.Animals this.SanDiegoZoo.Animals.Count is 2
this.ZooAverageAnimalWeight Its last stored result from either zoo; the highlighted assignment has not run
averageWeight Unavailable in this handler; inspect it after its declaration inside CalculateAverageAnimalWeight has run
totalWeight Unavailable in this handler; inspect it after its declaration inside CalculateTotalAnimalWeight has run
animal Unavailable in this handler; inspect it inside the total method after foreach selects a list item
B Press F11 to step into CalculateAverageAnimalWeight. After its declaration executes, ensure averageWeight is 0. Step into CalculateTotalAnimalWeight, then use F10 to follow the foreach loop.
1 Step through the method body. Ensure that the foreach loop processes two animals and totalWeight becomes approximately 3.77. The list Count remains 2.
2 Follow the return to CalculateAverageAnimalWeight. After the division statement executes, averageWeight is approximately 1.885.
3 Return to the button handler. After its assignment executes, this.ZooAverageAnimalWeight holds the returned value. Step over DisplayMessage and confirm the result is displayed.
C Check Your Work
1 While paused inside CalculateTotalAnimalWeight, inspect local totalWeight as the loop adds each animal’s weight.
2 Step out to CalculateAverageAnimalWeight. Confirm the returned total is used to compute local averageWeight.
3 Step out to the window handler. Confirm the returned average is stored in this.ZooAverageAnimalWeight.
4 Press F5 to continue. Stop debugging and remove the breakpoint before the next check.
Complete Zoo 2.4
21.Review the ending design
A Explain why the population uses a List<Animal> while the pen and tank keep their arrays. Use a fresh Como population and the shared-Dolly diagram as your example.
B Explain the difference between the first matching animal and the first matching pregnant animal. Explain why the average calculation checks Count before dividing.

The ending diagram includes the existing framework List<Animal> class and its Count property for context.

Ending Zoo 2.4 structure. Green marks new fields and methods; blue marks changed methods. Event handlers are abbreviated.
Ending structure — new and changed Zoo 2.4 members
  • New
  • Changed
  • Removed
22.Submit a zipped Visual Studio solution
A Save and build your .NET Framework 4.8 solution. Zip the solution and submit it to the Feedback System. Submit the Feedback System URL to the correct assignment in Canvas.