Exercise - Build and test a loop for entering new pet data
In this exercise, you develop code that controls the input of new ourAnimals array data. You calculate the initial values of your loop control variables and construct the loop that collects user specified data for the animals. The detailed tasks that you complete during this exercise are:
- Calculate petCount: write code that counts the number of pets in the
ourAnimalsarray that have assigned data. - Conditional messages: write code to display message output when
petCountis less thanmaxPets. - Outer loop: build a loop structure that will be used for entering new
ourAnimalsarray data. - Exit criteria: write code that evaluates the exit condition for the "enter new ourAnimals array data" loop.
- Verification test: perform verification tests for the code you develop in this exercise.
Important
You must complete the previous exercise in this module before starting this exercise.
Count the number of pets in the ourAnimals array
In this task, you establish the exit criteria for your data entry loop and you create a for loop that can be used to count the number of pets in ourAnimals that have assigned data.
Ensure that Visual Studio Code is open, and that your Program.cs file is visible in the Editor.
Locate the
switch(menuSelection)statement, and then find thecase "2":code line.Locate the
Console.WriteLine()statement that displays the "coming soon" message, and then replace it with a blank code line.On the blank code line that you created, to declare the
anotherPetandpetCountvariables, enter the following code:string anotherPet = "y"; int petCount = 0;These two variables control the iteration of a
whileloop that's used to enter new pet data. You initialize both variables as part of the declaration.anotherPetis initialized with a value ofyprior to the start of thewhileloop. It will receive a user assigned value, eitheryorninside thewhileloop.petCountrepresents the number of animals with assigned pet characteristics. It will be assigned a calculated value outside of yourwhileloop, and will be incremented by1inside thewhileloop each time a new animal is added to theourAnimalsarray.
Important
The scope of your variables should always be as narrow as possible. In the Contoso Pets application, you could scope
petCountat the application level rather than scoping to thecase "2":code block. The larger scope would enable you to accesspetCountfrom anywhere in the application. IfpetCountwas scoped at the application level, you could assign it a value when you create the sample data and programmatically manage its value throughout the remainder of the application. For example, when you find a home for a pet and remove the pet from theourAnimalsarray, you could reducepetCountby1. The question is, at what level should you scope a variable when you're unsure whether it will be used in other parts of your application? In this case, it's tempting to scopepetCountat the application level even though you aren't using it anywhere else. After all, scopingpetCountat the application level ensures that it's available if you do decide to use it elsewhere. Maybe you could scope other variables at the application level as well. That way, your variables are always in scope and accessible. So why not scope variables at the application level when you think they might be used later in the application? Scoping variables at a higher level than necessary can lead to problems. Elevated scope inflates the resource requirements of your application and may expose your application to unnecessary security risks. As your applications grow larger and more complex, they require more resources. Phones and computers allocate memory for these resources when they're in scope. As your applications become more "real-world", they become more accessible. Applications are often accessible from the cloud or other applications. Compounding these issues, applications are often left running when they aren't being used. It's important to keep an application's resource requirements under control and the security footprint as small as possible. Although today's operating systems do a great job of managing resources and securing applications, it's still best practice to keep your variables scoped to the level where they are actually needed. In your Contoso Pets app, if you decide to usepetCountmore broadly within the application, you can update your code to scopepetCountat a higher level. Remember to keep your variables scoped as narrowly as possible, and only increase their scope when it becomes necessary.On the code line below your variable declarations, to create a loop that iterates through the animals in the
ourAnimalsarray, enter the following code:for (int i = 0; i < maxPets; i++) { }This code should look familiar. You'll use this
forloop each time you iterate through theourAnimalsarray.Inside the code block of our
forloop, to check whether pet characteristics data has been assigned to an animal, enter the following code:if (ourAnimals[i, 0] != "ID #: ") { }Again, this code should look familiar. You'll use this
ifstatement each time you check whether pet characteristics have been assigned.Inside the code block of the
ifthat you created, to incrementpetCountby 1, enter the following code:petCount += 1;Take a minute to examine your completed
forloop.Your completed
forloop should look like the following code:for (int i = 0; i < maxPets; i++) { if (ourAnimals[i, 0] != "ID #: ") { petCount += 1; } }This code will loop through the
ourAnimalsarray checking for assigned data. When it finds an animal with data assigned, it incrementspetCounter.On the Visual Studio Code File menu, select Save.
Open the Integrated Terminal panel in Visual Studio Code and enter the command to Build your program.
To open the Integrate Terminal from the EXPLORER view, right-click Starter, and then select Open in Integrated Terminal. You can also use the View or Terminal menu to open the Integrated Terminal panel.
To Build your program, enter the
dotnet buildcommand from the Terminal command prompt.Fix any Build errors that you see reported before continuing.
Note
For now, you can ignore the Warning message about
anotherPetbeing assigned but never used. You'll add code that usesanotherPetlater in this exercise.If you have any build errors, remember that the Build error and warning messages tell you what the issue is and where you can find it. If you update your code, remember to save your changes before you rebuild.
Close the Terminal panel.
Display message output when petCount is less than maxPets
In this task, you check to see if petCount is less than maxPets and if it is, you display a message for the user.
On a blank code line below the
forloop that you created, to see ifpetCountis less thanmaxPets, enter the following code:if (petCount < maxPets) { }Inside the code block of the
ifstatement, to display a message to the user, enter the following code:Console.WriteLine($"We currently have {petCount} pets that need homes. We can manage {(maxPets - petCount)} more.");Application users are about to enter pet characteristics. This message provides important context.
Take a minute to review the
case "2":code branch of yourswitchstatement.At this point, your
case "2":code branch should look like the following code:case "2": // Add a new animal friend to the ourAnimals array string anotherPet = "y"; int petCount = 0; for (int i = 0; i < maxPets; i++) { if (ourAnimals[i, 0] != "ID #: ") { petCount += 1; } } if (petCount < maxPets) { Console.WriteLine($"We currently have {petCount} pets that need homes. We can manage {(maxPets - petCount)} more."); } Console.WriteLine("Press the Enter key to continue."); readResult = Console.ReadLine(); break;On the Visual Studio Code File menu, select Save.
Open the Integrated Terminal panel in Visual Studio Code and enter the command to Build your program.
Fix any Build errors that you see reported before continuing.
Again, you can ignore the Warning message about
anotherPetbeing assigned but never used. In the next task, you'll start building thewhileloop that is used to enter the data for one or more pets. The expression that you create for thewhileloop will useanotherPetand this Warning message will go away.Remember, warning messages are things that you should be concerned about, but they won't prevent you from running your program.
At the Terminal command prompt, enter the command to run your program.
Enter the
dotnet runcommand at the Terminal command prompt to run your program code.As long as your code doesn't generate a runtime error, the main menu of the app should now be displayed in the Terminal panel.
At the Terminal command prompt, enter 2
This value corresponds to your
case "2":code branch.Verify that the following message is displayed in the Terminal.
We currently have 4 pets that need homes. We can manage 4 more. Press the Enter key to continue.If you don't see the expected message displayed, review your code to identify and fix the issue. Save your changes, rebuild, and run the app again. Be sure to get code working as expected before you continue.
At the Terminal command prompt, press Enter to continue running your application.
Exit the application, and then close the Terminal panel.
Build a loop structure that will be used for entering new ourAnimals array data
In this task, you create a while loop that continues to iterate as long as anotherPet is equal to y and petCount is less than maxPets.
In the code Editor, create a blank code line below your
if (petCount < maxPets)code block.To begin the process of creating your new
whileloop, enter the following code:while (anotherPet == "y" && petCount < maxPets) { }On the Visual Studio Code File menu, select Save.
Open the Integrated Terminal panel in Visual Studio Code and enter the command to Build your program.
Notice that you no longer receive the Warning message about
anotherPetnot being used.If any Build errors or warnings were reported, fix the issues before continuing.
Check exit condition for new pets loop
In this task, you update the while (anotherPet == "y" && petCount < maxPets) code block. The new code increments petCount and then checks whether petCount is less than maxPets. If petCount is less than maxPets, you ask the user if they want to enter information for another pet, and ensure the response is either y or n. After the while (anotherPet == "y" && petCount < maxPets) code block, you check the value of petCount. If petCount is equal to maxPets, you inform the user that no more pets can be added.
Note
The code used to enter pet data is developed in the next exercise. For now, petCount is incremented as if data were being entered and saved to the ourAnimals array. This enables you to finish developing the code logic associated with the while loop.
Create a blank code line inside the code block of the
while (anotherPet == "y" && petCount < maxPets)loop that you created in the previous task.To increment
petCount, enter the following code:// increment petCount (the array is zero-based, so we increment the counter after adding to the array) petCount = petCount + 1;To check whether
petCountis less thanmaxPets, enter the following code:// check maxPet limit if (petCount < maxPets) { }Inside the code block of the
ifstatement that you created, to ask the user whether they want to add another pet, enter the following code:// another pet? Console.WriteLine("Do you want to enter info for another pet (y/n)");Below the
WriteLine()message that you entered, to read the user response and ensure that the user entered "y" or "n", enter the following code:do { readResult = Console.ReadLine(); if (readResult != null) { anotherPet = readResult.ToLower(); } } while (anotherPet != "y" && anotherPet != "n");Locate the
breakstatement that separatescase "2";fromcase "3";in yourswitchstatement.Notice the
Console.WriteLine()andConsole.ReadLine()statements at the end of ourcase "2";code.This code displays a message to the user and then pauses the application.
To enclose the
Console.WriteLine()andConsole.ReadLine()statements inside anifstatement, update your code as follows:if (petCount >= maxPets) { Console.WriteLine("Press the Enter key to continue."); readResult = Console.ReadLine(); } break; case "3":The value of
petCountis incremented inside thewhileloop. IfpetCountis equal tomaxPets, no more pets can be added to theourAnimalsarray. You should let the user know when this occurs.To inform the user that Contoso Pets has reached their capacity, update your code as follows:
if (petCount >= maxPets) { Console.WriteLine("We have reached our limit on the number of pets that we can manage."); Console.WriteLine("Press the Enter key to continue."); readResult = Console.ReadLine(); } break; case "3":Take a minute to review the code in your
whileloop and the user message that you've created.Your
while (anotherPet == "y" && petCount < maxPets)loop and code that displays the user message should look like the following code:while (anotherPet == "y" && petCount < maxPets) { // increment petCount (the array is zero-based, so we increment the counter after adding to the array) petCount = petCount + 1; // check maxPet limit if (petCount < maxPets) { // another pet? Console.WriteLine("Do you want to enter info for another pet (y/n)"); do { readResult = Console.ReadLine(); if (readResult != null) { anotherPet = readResult.ToLower(); } } while (anotherPet != "y" && anotherPet != "n"); } } if (petCount >= maxPets) { Console.WriteLine("We have reached our limit on the number of pets that we can manage."); Console.WriteLine("Press the Enter key to continue."); readResult = Console.ReadLine(); }On the Visual Studio Code File menu, select Save.
Open the Integrated Terminal panel in Visual Studio Code and enter the command to Build your program.
Fix any Build errors or warnings that you see reported before continuing.
Check your work
In this task, you run our application from the Integrated Terminal and verify that the looping and branching logic that you've created works as expected.
If necessary, open Visual Studio Code's Integrated Terminal panel.
At the Terminal command prompt, enter dotnet run
At the Terminal command prompt, enter 2
Verify that you see the following messages:
We currently have 4 pets that need homes. We can manage 4 more. Do you want to enter info for another pet (y/n)At the Terminal command prompt, enter n
Verify that your code exits the loop for entering new pets when you entered "n".
If your code logic is working as expected, you should see the main menu displayed in the Terminal.
If your code doesn't exit the loop when expected, press Ctrl + C in the Terminal to force execution to stop. You need to step through your code manually and trace the values of the exit criteria variables. Update your code if necessary to ensure that you exit the
whileloop when the user enters "n". Save your changes, rebuild your program, and run through the verification test to arrive back at this point.At the Terminal command prompt, enter 2
Once again, you'll see the following messages displayed:
We currently have 4 pets that need homes. We can manage 4 more. Do you want to enter info for another pet (y/n)At the Terminal command prompt, enter y
Take a minute to consider how
petCountis used in your code.You need to understand your code logic before you can validate your code.
In this case, your code logic relies on the relationship between
petCountandmaxPets. You know thatmaxPetsis assigned a value of8, but what aboutpetCount? The following items help to evaluate the logic you've implemented:You know that
petCountis4when you enter the first iteration of thewhileloop.You know that
petCountis incremented each time thewhileloop iterates.You know that the value assigned to
petCountand the way thatpetCountis incremented affect how data is stored in theourAnimalsarray. The following items explain the relationship betweenpetCountand the data stored inourAnimals:- The application adds four pets to the
ourAnimalsarray when it creates the sample data. - The application stores new data to the
ourAnimalsarray when the value ofpetCountis4. This isn't a bug. The code makes sense when you recall that array elements are zero-based. For example,ourAnimals[0,0]contains the pet ID for animal1andourAnimals[3,0]contains the pet ID for animal4. Therefore, whenpetCountis4you're storing data for the fifth pet. - The application will store pet data to the array before it increments
petCount. - The application increments
petCountbefore it prompts the user about adding another pet. - When the application displays the Do you want to enter info for another pet (y/n) prompt for the first time,
petCountis already set to5.
- The application adds four pets to the
If the user enters y at the first Do you want to enter info for another pet (y/n) prompt, you know that:
- The
while (anotherPet == "y" && petCount < maxPets)loop will iterate. You know the loop will iterate becauseanotherPet == "y"andpetCount < maxPets. - The value assigned to
petCountwill be incremented (when thewhileloop iterates). - The value assigned to
petCountwill be6(after the user enters y the first time).
- The
Keep this analysis of the code logic in mind as you continue testing the application.
Notice that the Terminal panel updates with the same "another pet?" message, but your code doesn't display an updated
petCount.The Terminal panel should now show the following output:
We currently have 4 pets that need homes. We can manage 4 more. Do you want to enter info for another pet (y/n) y Do you want to enter info for another pet (y/n)At the Terminal command prompt, enter y
When you enter
ya second time,petCountis incremented to7. SopetCountis still less thanmaxPetsAt the Terminal command prompt, enter y
When you enter
ya third time,petCountis incremented to8. SopetCountis now equal tomaxPetsVerify that your code exits the
whileloop when you enter y the third time.The Terminal panel should now show the following output:
We currently have 4 pets that need homes. We can manage 4 more. Do you want to enter info for another pet (y/n) y Do you want to enter info for another pet (y/n) y Do you want to enter info for another pet (y/n) y We have reached our limit on the number of pets that we can manage. Press the Enter key to continue.If your code doesn't exit the loop when expected, step through your code manually and trace the values of the exit criteria variables. Update your code to ensure that you exit the loop when
petCountreaches a value equal tomaxPets. Keep answering "y" until you know thatpetCountis equal tomaxPets, which has a default value of8.At the Terminal command prompt, press Enter to continue running your application.
Exit the application, and then close the Terminal panel.