연습 - 새 OurAnimals 배열 데이터를 읽고 저장하는 코드 작성
이 연습에서는 각 애완 동물 특성에 대한 데이터 항목 유효성 검사 루프를 개발한 다음 새 ourAnimals 배열 데이터를 저장합니다. 이 연습 중에 완료하는 자세한 작업은 다음과 같습니다.
- 종을 읽고 유효성을 검사합니다. 애완 동물 종을 입력하고 유효성을 검사하는 데 사용되는 루프 및 내부 코드 구조를 빌드합니다.
- 애완 동물 ID 생성: petCount 및 종 이름을 사용하여 petID 값을 생성하는 코드를 작성합니다.
- 나이 읽기 및 유효성 검사: 애완 동물의 나이를 입력하고 유효성을 검사하는 데 사용되는 루프 및 내부 코드 구조를 빌드합니다.
- 실제 설명을 읽고 유효성을 검사합니다. 애완 동물에 대한 물리적 설명을 입력하는 데 사용되는 루프 및 내부 코드 구조를 빌드합니다.
- 성격 설명을 읽고 유효성을 검사합니다. 애완 동물의 성격에 대한 설명을 입력하는 데 사용되는 루프 및 내부 코드 구조를 빌드합니다.
- 애칭 읽기 및 유효성 검사: 애완 동물에 대한 애칭을 입력하는 데 사용되는 루프 및 내부 코드 구조를 빌드합니다.
- 확인 테스트: 이 연습에서 개발하는 코드에 대한 확인 테스트를 수행합니다.
중요합니다
이 연습을 시작하기 전에 이 모듈의 이전 연습을 완료해야 합니다.
애완 동물 종을 읽고 유효성을 검사하는 루프를 빌드합니다.
이 작업에서는 사용자가 올바른 종 이름(개 또는 do)을 입력할 때까지 반복하는 루프를 만듭니 다. 무효화가 가능한 문자열 readResult를 재사용하여 Console.ReadLine() 입력을 캡처합니다. 또한 샘플 데이터를 생성할 animalSpecies 때 사용한 문자열 변수를 다시 사용합니다. 앱에 validEntry이라는 새 부울 변수를 추가합니다. do 루프의 종료 기준으로 평가되는 언어 식에서 validEntry를 사용합니다.
Visual Studio Code가 열려 있고 Program.cs 파일이 편집기에서 표시되는지 확인합니다.
while (anotherPet == "y" && petCount < maxPets)문을 찾은 후 최상단 코드 블록에 빈 코드 줄을 추가합니다.생성한 빈 코드 줄에
validEntry를 초기 값false으로 선언하려면 다음 코드를 입력하세요.bool validEntry = false;validEntry선언 아래 줄에서 종 데이터 입력을 위한do루프를 만들려면 다음 코드를 입력하십시오.// get species (cat or dog) - string animalSpecies is a required field do { } while (validEntry == false);명령문의
do코드 블록 내에서 표시 프롬프트를 만들고 사용자 입력을 읽으려면 다음 코드를 입력합니다.Console.WriteLine("\n\rEnter 'dog' or 'cat' to begin a new entry"); readResult = Console.ReadLine();값을 할당
readResultreadResult하기 전에 값animalSpecies이 Null이 아닌지 확인하려면 다음 코드를 입력합니다.if (readResult != null) { animalSpecies = readResult.ToLower(); }값 할당 아래 줄에서
animalSpecies유효한 종 이름을 포함하도록animalSpecies하려면 다음 코드를 입력합니다.if (animalSpecies != "dog" && animalSpecies != "cat") { validEntry = false; } else { validEntry = true; }완료된 종 이름 데이터 입력 루프를 다음 코드와 비교합니다.
// get species (cat or dog) - string animalSpecies is a required field do { Console.WriteLine("\n\rEnter 'dog' or 'cat' to begin a new entry"); readResult = Console.ReadLine(); if (readResult != null) { animalSpecies = readResult.ToLower(); if (animalSpecies != "dog" && animalSpecies != "cat") { //Console.WriteLine($"You entered: {animalSpecies}."); validEntry = false; } else { validEntry = true; } } } while (validEntry == false);Visual Studio Code 파일 메뉴에서 저장을 선택합니다.
Visual Studio Code에서 통합 터미널 패널을 열고 프로그램을 빌드하는 명령을 입력합니다.
빌드 오류 또는 경고가 보고된 경우 계속하기 전에 문제를 해결합니다.
동물 ID 값 생성
이 작업에서는 animalSpecies 변수와 petCount 변수를 사용하여 animalID에 할당할 값을 생성합니다.
종 이름 데이터 입력 루프의 코드 블록 아래에 빈 코드 줄을 추가합니다.
animalID값을 만들고 할당하려면, 다음 코드를 입력하십시오.// build the animal the ID number - for example C1, C2, D3 (for Cat 1, Cat 2, Dog 3) animalID = animalSpecies.Substring(0, 1) + (petCount + 1).ToString();Visual Studio Code 파일 메뉴에서 저장을 선택합니다.
애완 동물의 나이를 읽고 유효성을 검사하는 빌드 루프
이 작업에서는 do 반복되는 루프를 만들어, 사용자가 ? 또는 애완 동물의 나이를 나타내는 유효한 정수를 입력할 때까지 진행합니다. 무효화가 가능한 문자열 readResult를 재사용하여 Console.ReadLine() 입력을 캡처합니다. 또한 샘플 데이터를 생성할 animalAge 때 사용한 문자열 변수를 다시 사용합니다. 문자열 animalAge이 유효한 정수를 나타내는지 확인하려면 validEntry Boolean을 사용합니다. 숫자 값을 저장하기 위해 명명된 petAge 새 정수 변수를 선언합니다. 다시 한 번 validEntry 부울은 do 루프의 종료 기준으로 평가되는 언어 식에 사용됩니다.
변수에 값을
animalID할당하는 데 사용되는 줄 아래에 빈 코드 줄을 추가합니다.연령 데이터 입력에 대한 루프를
do만들려면 다음 코드를 입력합니다.// get the pet's age. can be ? at initial entry. do { } while (validEntry == false);명령문의
do코드 블록 내에서 명명petAge된 정수 변수를 선언하려면 다음 코드를 입력합니다.int petAge;선언
petAge아래 줄에서 메시지 프롬프트를 표시하고 사용자 입력을 읽으려면 다음 코드를 입력합니다.Console.WriteLine("Enter the pet's age or enter ? if unknown"); readResult = Console.ReadLine();값을 할당
readResultreadResult하기 전에 값animalAge이 null이 아닌지 확인하려면 다음 코드를 입력합니다.if (readResult != null) { animalAge = readResult; }값 할당 아래
animalAge줄에서 유효한 정수에 대해 테스트하기 전에 사용자가 입력했는지?확인하려면 다음 코드를 입력합니다.if (animalAge != "?") { validEntry = int.TryParse(animalAge, out petAge); } else { validEntry = true; }완료된 연령 데이터 입력 루프를 다음 코드와 비교합니다.
// get the pet's age. can be ? at initial entry. do { int petAge; Console.WriteLine("Enter the pet's age or enter ? if unknown"); readResult = Console.ReadLine(); if (readResult != null) { animalAge = readResult; if (animalAge != "?") { validEntry = int.TryParse(animalAge, out petAge); } else { validEntry = true; } } } while (validEntry == false);Visual Studio Code 파일 메뉴에서 저장을 선택합니다.
Visual Studio Code에서 통합 터미널 패널을 열고 프로그램을 빌드하는 명령을 입력합니다.
빌드 오류 또는 경고가 보고된 경우 계속하기 전에 문제를 해결합니다.
애완 동물의 물리적 설명을 읽고 유효성을 검사하는 빌드 루프
이 작업에서는 사용자가 애완 동물의 실제 설명을 나타내는 문자열 값을 입력할 때까지 반복하는 루프를 만듭니 do 다. 무효화가 가능한 문자열 readResult를 재사용하여 Console.ReadLine() 입력을 캡처합니다. 또한 샘플 데이터를 생성할 animalPhysicalDescription 때 사용한 문자열 변수를 다시 사용합니다. animalPhysicalDescription에 할당된 값을 do 루프의 종료 조건으로 평가되는 식에서 사용합니다.
연령 데이터 입력 루프의 코드 블록 아래에 빈 코드 줄을 추가합니다.
물리적 설명 데이터 입력에 대한 루프를
do만들려면 다음 코드를 입력합니다.// get a description of the pet's physical appearance/condition - animalPhysicalDescription can be blank. do { } while (animalPhysicalDescription == "");명령문의
do코드 블록 내에서 표시 프롬프트를 만들고 사용자 입력을 읽으려면 다음 코드를 입력합니다.Console.WriteLine("Enter a physical description of the pet (size, color, gender, weight, housebroken)"); readResult = Console.ReadLine();값을 할당
readResultreadResult하기 전에 값animalPhysicalDescription이 null이 아닌지 확인하려면 다음 코드를 입력합니다.if (readResult != null) { animalPhysicalDescription = readResult.ToLower(); }"tbd"값이 입력되었을 때animalPhysicalDescription에""값을 할당하려면 다음 코드를 입력하십시오.if (animalPhysicalDescription == "") { animalPhysicalDescription = "tbd"; }완료된 실제 설명 데이터 입력 루프를 다음 코드와 비교합니다.
// get a description of the pet's physical appearance/condition - animalPhysicalDescription can be blank. do { Console.WriteLine("Enter a physical description of the pet (size, color, gender, weight, housebroken)"); readResult = Console.ReadLine(); if (readResult != null) { animalPhysicalDescription = readResult.ToLower(); if (animalPhysicalDescription == "") { animalPhysicalDescription = "tbd"; } } } while (animalPhysicalDescription == "");Visual Studio Code 파일 메뉴에서 저장을 선택합니다.
Visual Studio Code에서 통합 터미널 패널을 열고 프로그램을 빌드하는 명령을 입력합니다.
빌드 오류 또는 경고가 보고된 경우 계속하기 전에 문제를 해결합니다.
애완 동물의 성격 설명을 읽고 유효성을 검사하는 빌드 루프
이 작업에서는 사용자가 애완 동물의 성격에 대한 설명을 나타내는 문자열 값을 입력할 때까지 반복하는 루프를 만듭니 do 다. 무효화가 가능한 문자열 readResult를 재사용하여 Console.ReadLine() 입력을 캡처합니다. 또한 샘플 데이터를 생성할 animalPersonalityDescription 때 사용한 문자열 변수를 다시 사용합니다. animalPersonalityDescription에 할당된 값을 do 루프의 종료 조건으로 평가되는 식에서 사용합니다.
물리적 설명 데이터 입력 루프의 코드 블록 아래에 빈 코드 줄을 추가합니다.
성격 설명 데이터 입력에 대한 루프를
do만들려면 다음 코드를 입력합니다.// get a description of the pet's personality - animalPersonalityDescription can be blank. do { } while (animalPersonalityDescription == "");명령문의
do코드 블록 내에서 표시 프롬프트를 만들고 사용자 입력을 읽으려면 다음 코드를 입력합니다.Console.WriteLine("Enter a description of the pet's personality (likes or dislikes, tricks, energy level)"); readResult = Console.ReadLine();값을 할당
readResultreadResult하기 전에 값animalPersonalityDescription이 null이 아닌지 확인하려면 다음 코드를 입력합니다.if (readResult != null) { animalPersonalityDescription = readResult.ToLower(); }"tbd"값이 입력되었을 때animalPersonalityDescription에""값을 할당하려면 다음 코드를 입력하십시오.if (animalPersonalityDescription == "") { animalPersonalityDescription = "tbd"; }완료된 성격 설명 데이터 입력 루프를 다음 코드와 비교합니다.
// get a description of the pet's personality - animalPersonalityDescription can be blank. do { Console.WriteLine("Enter a description of the pet's personality (likes or dislikes, tricks, energy level)"); readResult = Console.ReadLine(); if (readResult != null) { animalPersonalityDescription = readResult.ToLower(); if (animalPersonalityDescription == "") { animalPersonalityDescription = "tbd"; } } } while (animalPersonalityDescription == "");Visual Studio Code 파일 메뉴에서 저장을 선택합니다.
Visual Studio Code에서 통합 터미널 패널을 열고 프로그램을 빌드하는 명령을 입력합니다.
빌드 오류 또는 경고가 보고된 경우 계속하기 전에 문제를 해결합니다.
애완 동물의 애칭을 읽고 유효성을 검사하는 빌드 루프
이 작업에서는 사용자가 애완 동물의 애칭을 나타내는 문자열 값을 입력할 때까지 반복하는 루프를 만듭니 do 다. 무효화가 가능한 문자열 readResult를 재사용하여 Console.ReadLine() 입력을 캡처합니다. 또한 샘플 데이터를 생성할 animalNickname 때 사용한 문자열 변수를 다시 사용합니다. animalNickname에 할당된 값을 do 루프의 종료 조건으로 평가되는 식에서 사용합니다.
성격 설명 데이터 입력 루프의 코드 블록 아래에 빈 코드 줄을 추가합니다.
성격 설명 데이터 입력에 대한 루프를
do만들려면 다음 코드를 입력합니다.// get the pet's nickname. animalNickname can be blank. do { } while (animalNickname == "");명령문의
do코드 블록 내에서 표시 프롬프트를 만들고 사용자 입력을 읽으려면 다음 코드를 입력합니다.Console.WriteLine("Enter a nickname for the pet"); readResult = Console.ReadLine();값을 할당
readResultreadResult하기 전에 값animalNickname이 null이 아닌지 확인하려면 다음 코드를 입력합니다.if (readResult != null) { animalNickname = readResult.ToLower(); }"tbd"값이 입력되었을 때animalNickname에""값을 할당하려면 다음 코드를 입력하십시오.if (animalNickname == "") { animalNickname = "tbd"; }완료된 애칭 데이터 입력 루프를 다음 코드와 비교합니다.
// get the pet's nickname. animalNickname can be blank. do { Console.WriteLine("Enter a nickname for the pet"); readResult = Console.ReadLine(); if (readResult != null) { animalNickname = readResult.ToLower(); if (animalNickname == "") { animalNickname = "tbd"; } } } while (animalNickname == "");Visual Studio Code 파일 메뉴에서 저장을 선택합니다.
Visual Studio Code에서 통합 터미널 패널을 열고 프로그램을 빌드하는 명령을 입력합니다.
빌드 오류 또는 경고가 보고된 경우 계속하기 전에 문제를 해결합니다.
새 애완 동물 정보 저장
이 작업에서는 애완 동물 특성에 대해 입력한 값을 배열에 ourAnimals 저장합니다.
애칭 데이터 입력 루프의 코드 블록 아래에 빈 코드 줄을 추가합니다.
사용자가 지정한 데이터 값을 저장하려면 다음 코드를 입력합니다.
// store the pet information in the ourAnimals array (zero based) ourAnimals[petCount, 0] = "ID #: " + animalID; ourAnimals[petCount, 1] = "Species: " + animalSpecies; ourAnimals[petCount, 2] = "Age: " + animalAge; ourAnimals[petCount, 3] = "Nickname: " + animalNickname; ourAnimals[petCount, 4] = "Physical description: " + animalPhysicalDescription; ourAnimals[petCount, 5] = "Personality: " + animalPersonalityDescription;Visual Studio Code 파일 메뉴에서 저장을 선택합니다.
Visual Studio Code에서 통합 터미널 패널을 열고 프로그램을 빌드하는 명령을 입력합니다.
빌드 오류 또는 경고가 보고된 경우 계속하기 전에 문제를 해결합니다.
작업 확인
이 작업에서는 통합 터미널에서 애플리케이션을 실행하고 애완 동물 데이터 항목이 제대로 작동하는지 확인합니다.
필요한 경우 Visual Studio Code의 통합 터미널 패널을 엽니다.
터미널 명령 프롬프트에서 dotnet run을 입력합니다.
터미널 명령 프롬프트에서 2를 입력합니다.
터미널 패널이 다음 출력을 표시하도록 업데이트되었는지 확인합니다.
We currently have 4 pets that need homes. We can manage 4 more. Enter 'dog' or 'cat' to begin a new entry터미널 명령 프롬프트에 다음 값을 입력하고 각 후속 프롬프트가 표시되는지 확인합니다.
Enter 'dog' or 'cat' to begin a new entry프롬프트에서 dog 입력- 프롬프트에서
Enter the pet's age or enter ? if unknown에 ?을(를) 입력하십시오. - 프롬프트에서
Enter a physical description of the pet (size, color, gender, weight, housebroken)Enter 키를 누릅니다. - 프롬프트에서
Enter a description of the pet's personality (likes or dislikes, tricks, energy level)Enter 키를 누릅니다. - 프롬프트에서
Enter a nickname for the petEnter 키를 누릅니다.
터미널 패널은 다음과 같이 업데이트해야 합니다.
Enter 'dog' or 'cat' to begin a new entry dog Enter the pet's age or enter ? if unknown ? Enter a physical description of the pet (size, color, gender, weight, housebroken) Enter a description of the pet's personality (likes or dislikes, tricks, energy level) Enter a nickname for the pet Do you want to enter info for another pet (y/n)터미널 명령 프롬프트에서 n을 입력합니다 .
터미널 패널이 주 메뉴 옵션을 표시하도록 업데이트되었는지 확인합니다.
터미널 명령 프롬프트에서 1을 입력합니다.
터미널 패널이 다음 출력을 표시하도록 업데이트되었는지 확인합니다.
ID #: d1 Species: dog Age: 2 Nickname: lola Physical description: medium sized cream colored female golden retriever weighing about 65 pounds. housebroken. Personality: loves to have her belly rubbed and likes to chase her tail. gives lots of kisses. ID #: d2 Species: dog Age: 9 Nickname: loki Physical description: large reddish-brown male golden retriever weighing about 85 pounds. housebroken. Personality: loves to have his ears rubbed when he greets you at the door, or at any time! loves to lean-in and give doggy hugs. ID #: c3 Species: cat Age: 1 Nickname: Puss Physical description: small white female weighing about 8 pounds. litter box trained. Personality: friendly ID #: c4 Species: cat Age: ? Nickname: Physical description: Personality: ID #: d5 Species: dog Age: ? Nickname: tbd Physical description: tbd Personality: tbd Press the Enter key to continue새로 추가한 애완 동물 정보가 표시되지 않으면 데이터를Animals 배열에 저장하는 코드 줄을 포함했는지 확인하고 petID를 생성하는 코드 줄을 포함했는지 확인합니다.
개와 고양이에 대한 추가 동물 설명을 만들 수 있고 동물의 특성이 배열에
ourAnimals저장되고 있는지 확인합니다.애플리케이션을 종료한 다음 터미널 패널을 닫습니다.
이 단계별 프로젝트를 완료한 것을 축하합니다! 애플리케이션 디자인 목표를 달성하기 위해 선택 문과 반복 문을 결합하는 애플리케이션을 만들었습니다. 애플리케이션에는 300개가 넘는 줄이 포함되어 있으며 전문 애플리케이션에서 찾을 수 있는 작업을 수행합니다. 이 프로젝트를 완료하는 것은 중요한 성과를 나타냅니다. 앞으로도 계속 정진하세요!