3.1 Zoo Learning Activity [3 hours 30 minutes]

Validate animal input
1.Prepare your Zoo 3.1 solution [5 minutes]

Continue from your completed Zoo 2.7. Add a form that accepts a new platypus for San Diego Zoo. Clean text, convert numeric input safely, report the first invalid value, and add an animal only after every check passes.

A Copy your completed Zoo 2.7 folder and rename the copied folder and solution for Zoo 3.1 using your last name. Open the copied solution and restore its NuGet packages. Keep .NET Framework 4.8.
B In MainWindow.xaml, change the window title to Title="Programming Concepts 3: Zoo 3.1 Lastname" , replacing Lastname with your last name. Keep the existing size for this initial check.
Combined unchanged Zoo 2.7 classes. Unrelated members use [...]. The private animals list and public Pen and Tank array fields retain their existing roles.
Starting structure — combined Zoo 2.7 classes
C Check Your Work
1 Select Build > Build Solution and resolve build errors before proceeding. Run the application and click New San Diego Zoo. The creation message reports one animal in the tank; San Diego's Get animal count reports two animals in its population list.

Patti occupies tank cell [1, 1]; Harold belongs to the list but has no tank cell. This distinction is already present in Zoo 2.7.

2 Stop debugging before making the following source edits.
Enter an animal through the window
Acceptance Criteria
  • The form supplies type, name, sex, age, weight, and pregnancy state.
  • The business method cleans and validates all input before adding one animal.
  • Blank names, bad numbers, invalid ranges, inconsistent pregnancy, and duplicate names produce useful feedback.
2.Plan validation before changing state [10 minutes]
A Read the validation design and distinguish the window's job from the zoo's job.

The window reads controls and displays a message. Zoo.AddAnimalFromValues accepts their raw values, checks them, and returns feedback. Validation decides whether input is acceptable. Normalization cleans an acceptable representation: trim spaces around a display name and compare letter case consistently.

Zoo validation fields and complete method signatures with indented continuation lines. Bold green text and plus icons mark three new fields and two new methods. The existing readonly animals list references Animal. Unrelated fields and operations are represented by [...].
Validation fields, new method signatures, and existing collaborators
B Check Your Work
1 Locate the existing AddAnimal method in Zoo.cs. It changes the population list. The new method must reach this call only after all validation succeeds.
3.Add the animal-entry controls [20 minutes]
A Read how the controls supply values.

Each new name attribute supplies the control field used from code-behind. A TextBox's Text is a string even when it displays digits. The ListBox's selected value supplies Platypus because its selected-value path is Content. The ListBox contains one ListBoxItem. SelectedIndex 0 selects that first item, SelectionMode Single permits only one selection, and SelectedValuePath Content supplies that item's displayed string. IsEnabled False locks this currently supported animal type. These selection settings are supplied completely in the markup below. A CheckBox can be checked, unchecked, or indeterminate; this.isPregnantCheckBox.IsChecked == true supplies a Boolean that is true only when checked. This comparison supplies the Boolean parameter required by the zoo method.

B In MainWindow.xaml, insert the following complete Grid inside the San Diego StackPanel, immediately before its birthing-room temperature label.

Set the window's Height="825" . Preserve the outer Grid, existing controls, and event hookups. The new Grid has its own rows and columns.

Animal-entry form
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Text="New animal:" Width="80" Grid.Column="0" Grid.Row="0" Margin="3,10,3,0"/>
    <TextBlock Text="Type" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    <ListBox x:Name="animalTypeListBox" Grid.Column="1" Grid.Row="1" Margin="3" Height="28" SelectionMode="Single" SelectedValuePath="Content" SelectedIndex="0" IsEnabled="False">
        <ListBoxItem Content="Platypus"/>
    </ListBox>
    <TextBlock Text="Name" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    <TextBox x:Name="nameTextBox" Grid.Column="1" Grid.Row="2" Margin="3" Text="Paddy"/>
    <TextBlock Text="Sex" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    <TextBox x:Name="sexTextBox" Grid.Column="1" Grid.Row="3" Margin="3" Text="Female"/>
    <TextBlock Text="Age" Grid.Column="0" Grid.Row="4" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    <TextBox x:Name="ageTextBox" Grid.Column="1" Grid.Row="4" Margin="3" Text="2"/>
    <TextBlock Text="Weight" Grid.Column="0" Grid.Row="5" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    <TextBox x:Name="weightTextBox" Grid.Column="1" Grid.Row="5" Margin="3" Text="31.5"/>
    <TextBlock Text="Is Pregnant" Grid.Column="0" Grid.Row="6" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    <CheckBox x:Name="isPregnantCheckBox" Grid.Column="1" Grid.Row="6" Margin="3"/>
    <Button x:Name="addAnimalToSanDiegoZooButton" HorizontalAlignment="Right" Margin="5,3" Grid.Column="1" Grid.Row="7" Width="75" Content="Add" Click="addAnimalToSanDiegoZooButton_Click"/>
</Grid>
C Check Your Work
1 Inspect the XAML: the initial name is Paddy, sex is Female, age is 2, weight is 31.5, and the pregnancy CheckBox is unchecked. The Click name exactly matches the new handler shown later. This is a source check, not a runtime check yet.
Reject invalid entries before adding an animal
Acceptance Criteria
  • A failed entry returns its first validation message and does not add, move, feed, or replace an existing animal.
  • Age must be a whole number at least zero. Weight must be numeric, strictly positive, and finite.
  • Names are trimmed for storage and compared without letter-case differences for uniqueness within this zoo.
  • A successful entry adds one animal to the list; it does not place that animal in the tank.
4.Define the validation limits [5 minutes]
A In Zoo.cs, add the three private readonly fields shown in the focused validation class diagram.

Initialize availableAnimalType to "Platypus", minimumAnimalAge to 0, and minimumAnimalWeight to 0. The minimum age is inclusive; the minimum weight is exclusive. Keep the existing animal list and constructor initialization. The new method uses these fields to keep its rules in one place.

B Check Your Work
1 From those declarations, age 0 may pass, while weight 0 must fail. A type other than Platypus must fail. Do not add arbitrary maximum-age or maximum-weight business rules.
5.Find an existing animal by name [15 minutes]
A Add the public method FindAnimalByName(string name) to Zoo.cs, using its exact signature in the class diagram and the flow below. Keep the existing type-based searches.
Initialize foundAnimal to null. If name exists, search animals using non-null stored names and lowercase comparison. On the first match store the existing reference and break; return after the loop.
Name search — return the first existing reference
1 Initialize the local Animal foundAnimal = null;. This supplies the result when no match is found or the input name is null. C# local variables must be assigned before they are read; they do not receive a field's automatic default initialization.
2 Follow the foreach and guards in the activity. On the first match, store the existing animal reference, then break out of the loop. Return foundAnimal after the loop and outer guard, including the no-match path.
B Check Your Work
1 Source trace only: with Patti and Harold in the list, name pAtTi returns Patti's existing reference; an absent name and a null name return null. A leading space is not removed by this helper. Check that no assignment changes animal.Name and no list entry is added.
6.Validate and commit the animal entry [40 minutes]
A Add the public AddAnimalFromValues method to Zoo.cs using the full parameter list in the focused class diagram. It returns a string message. Implement the following three activities as successive parts of this one method.
1 Implement the text checks first, in the order shown. Return each exact message from the activity at its failure branch.
AddAnimalFromValues part one. Reject unsupported type, blank name, or blank or unsupported sex with exact feedback. Trim the display name and normalize sex. Continue to numeric validation without changing the zoo.
Entry validation, part 1 — type and text
2 Declare int age; and double weight; after the sex checks. Begin by converting age with Parse and weight with TryParse, as explained below.
First age-conversion statement
age = int.Parse(ageText);
Weight-conversion syntax bridge
if (!double.TryParse(weightText, out weight))
{
    return "Invalid entry: Weight must be a number.";
}

Follow the initial numeric activity below: convert age, check its lower boundary, then convert and check weight. Keep each local declaration only once. Complete the connected Add handler before running the application.

First numeric implementation. Parse age directly, range-check age, then TryParse and range-check weight. Invalid age text interrupts this initial version before an animal is created.
First numeric version — direct age conversion and checked weight conversion
3 Continue in the same method with the pregnancy and duplicate-name checks, then create and add the animal exactly once as shown.
AddAnimalFromValues final part. Reject male pregnancy and duplicate names. Only then construct the animal, optionally MakePregnant, AddAnimal once, and return the success message.
Entry validation, part 3 — consistency, uniqueness, and addition

Declare Animal animal = new Animal(type, sex, name, age, weight); only after all checks. If requested, call MakePregnant on the new local animal before this.AddAnimal(animal). Return the success message using the stored animal's name and this zoo's name. Keep AddAnimal, MakePregnant, and all existing creation helpers unchanged.

B Check Your Work
1 Source trace only: a blank name and bad age together return the name message, because that check runs first. Neither numeric conversion nor animal construction is reached.
2 Source trace only: follow a valid female entry and a male entry with pregnancy checked. The valid entry reaches construction and one addition; male pregnancy returns before both. Failed attempts must leave the list and existing objects unchanged.
7.Connect the Add button to validation [10 minutes]
A Add the following complete event handler inside MainWindow in MainWindow.xaml.cs. Do not place it inside another method.
Add-button event handler
/// <summary>
/// Adds an animal to the San Diego Zoo using the values entered in the controls.
/// </summary>
/// <param name="sender">The object that raised the event.</param>
/// <param name="e">The event data.</param>
private void addAnimalToSanDiegoZooButton_Click(object sender, RoutedEventArgs e)
{
    string message;

    if (this.sanDiegoZoo != null)
    {
        if (this.animalTypeListBox.SelectedValue == null)
        {
            this.DisplayMessage("Select an animal type.");
            return;
        }

        message = this.sanDiegoZoo.AddAnimalFromValues(
            this.animalTypeListBox.SelectedValue.ToString(),
            this.nameTextBox.Text,
            this.sexTextBox.Text,
            this.ageTextBox.Text,
            this.weightTextBox.Text,
            this.isPregnantCheckBox.IsChecked == true);
    }
    else
    {
        message = "Create the San Diego Zoo before adding a platypus.";
    }

    this.DisplayMessage(message);
}
B Check Your Work
1 Select Build > Build Solution. Confirm there are no build errors and the new Click value resolves to exactly one handler. Review warnings with your course tools; do not remove existing warning suppressions or change unrelated code to complete this feature.
2 Start debugging with F5. Before clicking either creation button, click Add. Confirm the information box says Create the San Diego Zoo before adding a platypus. and the application stays open.
8.Observe a conversion failure and improve validation [15 minutes]
A Locate age = int.Parse(ageText); in AddAnimalFromValues. Before running the checks, predict what will happen when the age text is abc instead of a whole number.
B Check Your Work
1 Stop debugging, build, and start debugging again with F5. Click New San Diego Zoo. Enter Paddy, Female, 2, and 31.5, leaving pregnancy unchecked, then click Add. Confirm Added Paddy to San Diego Zoo.. Parse can convert valid whole-number text.
2 Click New San Diego Zoo again. Restore all default form values, then change only age to abc and click Add. Observe where Visual Studio pauses or reports the unhandled error. Locate age = int.Parse(ageText); in Zoo.cs. The error is a FormatException; its wording may vary. No message explaining the invalid age appears in the application; conversion interrupts this first version.
3 While the failed statement and error are visible, compare the result with your prediction. Identify the input that could not be converted and explain why execution did not reach the normal success message or add an animal. Do not continue clicking controls while the debugger is paused.
C Stop debugging with Shift+F5. Change age conversion to report failure through the application: replace age = int.Parse(ageText); with the following guard.
Improved age conversion
if (!int.TryParse(ageText, out age))
{
    return "Invalid entry: Age must be a whole number.";
}

int.TryParse follows the same Boolean-and-out pattern you used for weight. It supplies an integer when conversion succeeds. On failure it returns false and supplies zero, so return the whole-number message before running the age-range check or creating an animal. Keep the existing age and weight declarations, then rebuild.

AddAnimalFromValues part two. TryParse age and weight, then check inclusive zero age and strictly positive finite weight. Each failure returns its exact message before state changes.
Completed numeric validation — checked age and weight conversion
D Check Your Work
1 Start debugging again. Click New San Diego Zoo, restore all default form values, change age to abc, and click Add. This time the application stays usable and displays Invalid entry: Age must be a whole number.. Click San Diego's Get animal count and confirm it remains 2.
2 Continue this case without recreating the zoo. Change age to 2 and click Add. Expect Added Paddy to San Diego Zoo. and population count 3. Confirm age now uses int.TryParse before proceeding.

The following sequence describes the completed TryParse version. Invalid age text now returns feedback through the window instead of interrupting the initial Parse statement.

Completed TryParse version. The Add handler checks zoo existence and selection, passes raw form text to Zoo, and displays the returned message. Zoo checks all inputs before constructing and adding one animal. A rejection leaves the existing population unchanged.
Completed Add click — validate before construction and list mutation
Test accepted, rejected, and corrected entries
9.Check the validation rules and boundaries [45 minutes]
A Check Your Work
1 Stop and restart the application. Click New San Diego Zoo. Do not feed, wake, move, or give birth. Enter Paddy, Female, 2, and 31.5, leaving pregnancy unchecked; click Add.
2 Confirm Added Paddy to San Diego Zoo.. Click San Diego's Get animal count: expect Animal count: 3. Click its Get average animal weight: expect approximately 11.7566667. The tank map stays unchanged with Patti at [1, 1].
After adding Paddy to a newly created San Diego Zoo, the population list contains Patti, Harold, and Paddy. Only Patti occupies tank cell 1,1. Paddy is not placed in the tank. Counts are list 3 and occupied cells 1.
List population and tank occupancy after one successful addition
3 Continue this same case: click Add again with the same values. Expect Invalid entry: Animal names must be unique within the zoo.. Click the count and average buttons again: count remains 3 and average remains approximately 11.7566667.
B Check Your Work
1 Run every listed input below as an independent case. If a row lists alternatives, such as blank, abc, or 2.5, run a separate trial for each alternative. Click New San Diego Zoo, restore Paddy, Female, 2, 31.5, and pregnancy unchecked, then change only the stated input and click Add. Read the error before clicking another button, then check that San Diego's count is still 2 and average is still 1.885.

The creation button resets zoo objects but does not reset form controls, so restore all fields explicitly for every trial. With no feeding, wake, movement, or birth, the map must still contain only Patti at [1, 1].

Rejected input cases
Change to the restored form Exact feedback
Clear the name, or enter only spaces Invalid entry: Enter a name.
Clear sex, enter only spaces, or enter Other Invalid entry: Enter Male or Female for sex.
Age blank, abc, 2.5, or 2147483648 Invalid entry: Age must be a whole number.
Age -1 Invalid entry: Age must be zero or greater.
Weight blank or abc Invalid entry: Weight must be a number.
Weight 0 or -0.1 Invalid entry: Weight must be greater than zero and finite.
Sex Male and pregnancy checked Invalid entry: A male platypus cannot be pregnant.
Name with spaces around pAtTi Invalid entry: Animal names must be unique within the zoo.
Blank name and age abc together Invalid entry: Enter a name.
2 Click New San Diego Zoo and restore all default form values, then change age to abc. Click Add and confirm its whole-number feedback. Without recreating the zoo, correct age to 2 and click Add. Expect the success message and count 3. No partial animal from the failed attempt may remain.
C Check Your Work
1 For each row below, click New San Diego Zoo, restore all default form values, apply the listed changes, and click Add. Expect Added Paddy to San Diego Zoo. and list count 3 each time.
Accepted boundaries and normalization
Changes to restored form Expected stored values or meaning
Age 0 Age is accepted at its inclusive lower boundary
Age 1 Age is accepted above its lower boundary
Age 2147483647 Largest int value is accepted; the next integer fails conversion
Weight 0.1 Positive finite weight is accepted above the exclusive zero boundary
Spaces around Paddy and mixed-case sex fEmAlE Stored name Paddy, stored sex Female
Pregnancy checked with sex Female New animal's IsPregnant is true; list still gains only one entry
Sex Male with pregnancy unchecked Stored sex Male, IsPregnant false
2 To inspect the stored values for an accepted case, stop debugging and set a breakpoint on the success return in AddAnimalFromValues. Restart, click New San Diego Zoo, restore the defaults, then repeat the chosen acceptance row. At the pause, addition has completed. Add animal to Watch and expand it to inspect Name, Sex, IsPregnant, Weight, and the private age field. Remove the breakpoint and resume before the next independent case.
3 Source trace only: the disabled type list cannot select Dingo, and TextBox Text normally supplies strings rather than null. Trace those guards in AddAnimalFromValues with a type of Dingo and, separately, a null name. Expect the unsupported-type and blank-name messages respectively; neither reaches addition. Do not modify the form to create a permanent test caller.
4 Source trace only: if TryParse recognizes NaN or positive infinity, follow the combined range test. It must reject both before construction. If the text is not recognized under the current culture, the conversion guard returns the numeric-input message instead. No special input spelling is required for a runtime check.
10.Follow raw input through validation [25 minutes]
A Check Your Work
1 Stop debugging. In MainWindow.xaml.cs, set a breakpoint on the message = this.sanDiegoZoo.AddAnimalFromValues(...) call inside the new Add handler. Press F5, click New San Diego Zoo, restore the defaults, enter spaces around Paddy and mixed-case fEmAlE, and leave pregnancy unchecked. Click Add.
2 While paused, open Debug > Windows > Watch > Watch 1 and add the expressions below before stepping. Do not invoke methods or change values through Watch.
Inspect the caller before conversion
Expression in MainWindow Expected observation
this.nameTextBox.Text Paddy with the spaces you entered
this.sexTextBox.Text fEmAlE with the exact spacing you entered
this.ageTextBox.Text The string 2, not an int yet
this.sanDiegoZoo.AnimalCount 2
3 Once inside AddAnimalFromValues, add the following Watch expressions before advancing to their observations. Use F10 to execute statements, inspecting each value after its assignment runs.
Inspect normalization, conversion, and commit
Expression in Zoo Observe after Expected value
nameText Entering the method Original name including spaces
name The trimmed-name assignment Paddy without outside spaces
sex The lowercase assignment, then the matching branch assignment female, then Female
age Successful int.TryParse check 2
weight Successful double.TryParse check 31.5
this.animals.Count Before constructing the new animal 2
animal.Name The new Animal assignment Paddy
animal.IsPregnant The unchecked pregnancy branch is skipped false
this.animals.Count The AddAnimal call executes 3
4 Follow the method's success return to MainWindow. After the call assignment executes, inspect message: Added Paddy to San Diego Zoo.. Continue to the display call and execute it; the information box must show that message. Remove the Add-call breakpoint, then press F5 to resume before touching other controls.
B Check Your Work
1 Stop debugging. In Zoo.cs, set a breakpoint on the age TryParse condition in AddAnimalFromValues. Restart, click New San Diego Zoo, restore all default form values, change age to abc, and click Add. When paused, add ageText, age, and this.animals.Count to Watch before stepping.
2 Before conversion, ageText is abc and list count is 2; age's pre-assignment display is not required to be a particular value. Step over the condition. Conversion reports false, age receives 0, and execution enters the whole-number error branch rather than the later range check or constructor.
3 Follow the error return back to the handler. In MainWindow, inspect message after assignment: Invalid entry: Age must be a whole number.. The zoo's AnimalCount is still 2. Remove the breakpoint and resume; the message appears and the application remains usable.
Preserve existing behavior and finish
11.Check the existing zoo features [15 minutes]
A Check Your Work
1 Stop and restart with no breakpoints. Create both zoos. Como's list count is 3 and its creation message reports one occupied pen space; San Diego's list count is 2 and its creation message reports one occupied tank cell. Adding Paddy to San Diego changes its list count to 3 while Como's stays 3.
2 Stop and restart the application, then create both zoos. Before feeding, click Flora, fill vending machine and expect Flora filled the vending machine by adding 0 bag(s) of food.. Click Betty, fill vending machine and expect the same message beginning with Betty. Each machine was filled during creation and has no room for another full bag. Then click Darla, feed dingo and expect Darla fed Dingo at Como Zoo.. Click Dave, feed platypus and expect Dave fed Platypus at San Diego Zoo.. Read each message before the next action.
3 Restart and create both zoos. Before moving either mother, give birth once in each zoo. Each occupied-area count becomes 2. Como's list count becomes 4 and San Diego's becomes 3. Attempt the same births again: occupied baby spaces block them.
4 Stop and restart, then create both zoos without feeding, waking, or giving birth. Click Como's right arrow once: Dolly moves from pen index 1 to index 2, the X marker follows, and the message reports pen position 3 with one occupied pen space. Click left once to return to index 1. Click San Diego's right arrow once: Patti moves from [1, 1] to [1, 2], the X marker follows, and the message reports tank row 2, column 3 with one occupied tank cell. Click left once to return to [1, 1]. Population counts remain Como 3 and San Diego 2.
5 Click New San Diego Zoo to reset its temperature to 77.0. Click its temperature plus button once: expect 77.5; click minus once: expect 77.0. Continue clicking plus until 85.0, then click plus again: it stays 85.0. Click New San Diego Zoo again to return to 77.0, then use minus to reach 55.0; an additional minus must leave it at 55.0. No feeding, waking, or birth is part of this check.
Combined Zoo 3.1 ending classes. Three readonly validation fields and two methods are new in Zoo. MainWindow adds the Add event handler. Unrelated members use [...]; all existing class relationships are retained.
Ending structure — combined Zoo 3.1 classes
B Check Your Work
1 Compare the two new Zoo methods and three validation fields with the diagrams. Compare your Add handler with the complete handler listing in this page; the class diagram groups event handlers under [...]. All other business classes retain their Zoo 2.7 behavior. Resolve build errors and review course analyzer feedback before submission.
12.Save and submit Zoo 3.1 [5 minutes]
A Save all files and ZIP your completed Zoo 3.1 solution folder. Remove any temporary experiments and breakpoints first.