연습 - 시작 코드 검토
개발 프로세스의 첫 번째 단계에서는 Starter 프로젝트 폴더에 제공된 코드를 검토합니다.
Program.cs 파일의 내용 검토
Program.cs 파일에는 작업 중인 애플리케이션의 예비 버전이 포함되어 있습니다. 이 코드에는 애플리케이션에 대한 샘플 데이터를 생성하고 표시하는 기능이 포함되어 있으며 애플리케이션의 주요 기능을 정의하는 메뉴 옵션 목록이 표시됩니다.
Visual Studio Code에서 "GuidedProject" 폴더(Guided-project-Work-with-variable-data-CSharp-main)가 열려 있는지 확인합니다.
"준비" 단원(이 모듈의 이전 단원)에는 단계별 프로젝트의 초기 시작 지점을 다운로드하고 Visual Studio Code 폴더를 여는 프로세스를 설명하는 설치 섹션이 포함되어 있습니다. 필요한 경우 돌아가서 설정 지침을 따릅니다.
"탐색기" 보기에서 "Starter" 폴더를 확장한 다음, "Program.cs"을 선택합니다.
Program.cs 파일을 선택하면 파일 내용이 탐색기 오른쪽의 기본 편집기 영역에서 열립니다.
탐색기 보기가 열려 있지 않으면 Visual Studio Code의 맨 왼쪽에 있는 작업 표시줄에서 탐색기 보기를 선택/열 수 있습니다. 탐색기는 작업 표시줄의 맨 위 아이콘입니다.
Program.cs 파일의 맨 위에 있는 초기 변수 선언을 검토하려면 몇 분 정도 걸립니다.
// #1 the ourAnimals array will store the following: string animalSpecies = ""; string animalID = ""; string animalAge = ""; string animalPhysicalDescription = ""; string animalPersonalityDescription = ""; string animalNickname = ""; // #2 variables that support data entry int maxPets = 8; string? readResult; string menuSelection = ""; // #3 array used to store runtime data, there is no persisted data string[,] ourAnimals = new string[maxPets, 6];먼저 주석(주석 #1) 뒤에 변수 목록이 표시됩니다. 이러한 변수는
animalSpeciesanimalNickname애완 동물 특성의 값을 명명ourAnimals된 다차원 문자열 배열 내에 보관하는 데 사용되며 길이가 0인 문자열""을 포함하도록 초기화됩니다.ourAnimals배열 선언은 코드에서 약간 더 아래로 내려갔습니다.다음 변수 그룹(주석 #2 아래)은 샘플 데이터를 생성하고, 사용자 입력을 읽고, 주요 프로그램 루프의 종료 조건을 설정하는 데 도움이 되는
string변수와int변수의 혼합입니다. 코드 줄을string? readResult;확인합니다.?문자를 사용하여 nullable 형식에 대한 지원을 통해 일반적으로 nullable이 아닌 변수 형식(int, string, bool,...)을 변환합니다.비고
메서드를
Console.ReadLine()사용하여 사용자가 입력한 값을 읽을 때 프로젝트를 빌드할 때 코드 컴파일러에서 경고를 생성하지 않도록 nullable 형식 문자열을 사용하도록string?설정하는 것이 가장 좋습니다.마지막 변수(주석 #3 아래)는 이름이
ourAnimals2차원 문자열 배열입니다. maxPets로 정의된 행 수를 8로 초기화했습니다. 처음에 저장하는 특성 수는 6개입니다. 6가지 특성은 샘플 코드에서 검사한 문자열 변수의 수와 일치하지만, 필드를suggestedDonation추가하려면 특성 수를 확장해야 합니다.Program.cs 파일을 아래로 스크롤하여 코드 블록 내에 선택 구문이 포함된 루프를 살펴봅니다.
코드 샘플은 공간을 절약하기 위해 단축된 버전입니다.
// #4 create sample data ourAnimals array entries for (int i = 0; i < maxPets; i++) { switch (i) { case 0: animalSpecies = "dog"; animalID = "d1"; animalAge = "2"; animalPhysicalDescription = "medium sized cream colored female golden retriever weighing about 45 pounds. housebroken."; animalPersonalityDescription = "loves to have her belly rubbed and likes to chase her tail. gives lots of kisses."; animalNickname = "lola"; break; case 1: animalSpecies = "dog"; animalID = "d2"; animalAge = "9"; animalPhysicalDescription = "large reddish-brown male golden retriever weighing about 85 pounds. housebroken."; animalPersonalityDescription = "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."; animalNickname = "gus"; break; // case 2: deleted for brevity // case 3: deleted for brevity default: animalSpecies = ""; animalID = ""; animalAge = ""; animalPhysicalDescription = ""; animalPersonalityDescription = ""; animalNickname = ""; break; } ourAnimals[i, 0] = "ID #: " + animalID; ourAnimals[i, 1] = "Species: " + animalSpecies; ourAnimals[i, 2] = "Age: " + animalAge; ourAnimals[i, 3] = "Nickname: " + animalNickname; ourAnimals[i, 4] = "Physical description: " + animalPhysicalDescription; ourAnimals[i, 5] = "Personality: " + animalPersonalityDescription; }for루프는maxPets변수를 사용하여 주석 # 4 다음에 반복 횟수에 상한을 설정합니다.또한
switch구성이 샘플 데이터 집합의 애완 동물에 대해 다양한 특성을 정의할 수 있도록 코드의 흐름을 선택적으로 분기합니다.문을 사용하여
switch루프의for처음 네 번의 반복에 대해 서로 다른 값을 정의합니다. 샘플 데이터 처리 후에는 모든 특성이 비어 있거나 길이가 0인 문자열이 됩니다.동물 특성 변수의 값은 루프 아래쪽
for에 있는 ourAnimals 배열에 할당됩니다.Visual Studio Code에서 코드 파일의 아래쪽으로 스크롤합니다. 메뉴 옵션을 표시하고 사용자 선택 항목의 입력을 캡처하는 데 사용되는 코드를 검사합니다.
다음 코드를 확인해야 합니다.
// #5 display the top-level menu options do { // NOTE: the Console.Clear method is throwing an exception in debug sessions Console.Clear(); Console.WriteLine("Welcome to the Contoso PetFriends app. Your main menu options are:"); Console.WriteLine(" 1. List all of our current pet information"); Console.WriteLine(" 2. Display all dogs with a specified characteristic"); Console.WriteLine(); Console.WriteLine("Enter your selection number (or type Exit to exit the program)"); readResult = Console.ReadLine(); if (readResult != null) { menuSelection = readResult.ToLower(); } // use switch-case to process the selected menu option switch (menuSelection) { case "1": // list all pet info for (int i = 0; i < maxPets; i++) { if (ourAnimals[i, 0] != "ID #: ") { Console.WriteLine(); for (int j = 0; j < 6; j++) { Console.WriteLine(ourAnimals[i, j]); } } } Console.WriteLine("\n\rPress the Enter key to continue"); readResult = Console.ReadLine(); break; case "2": // Display all dogs with a specified characteristic"); Console.WriteLine("\nUNDER CONSTRUCTION - please check back next month to see progress."); Console.WriteLine("Press the Enter key to continue."); readResult = Console.ReadLine(); break; default: break; } } while (menuSelection != "exit");잠시 시간을 내어 두
case명령문을 검토하세요.애플리케이션의 제한된 버전으로 작동하는 메뉴 옵션은 두 가지뿐입니다. 시작 애플리케이션은 기능 프로토타입을 실행하고 테스트하는 데 필요한 기능만 제공합니다.
코드
readResult = Console.ReadLine();줄 뒤에 null 값이 있는지 확인합니다.메서드를
Console.ReadLine()사용하는 코드에는 프로젝트를 빌드할 때 코드 컴파일러가 경고를 생성하지 않도록 nullable 문자열readResult로 설정된 값이 있습니다.
작업 확인
터미널 명령 프롬프트 빌드에서 시작 코드 콘솔 앱을 테스트하고 다음
dotnet run을 입력하여 하나의 명령으로 프로젝트 코드를 실행합니다.비고
터미널 프롬프트를 시작 폴더에서 열어야 하며 터미널은 과 유사해야 합니다.
..\ArrayGuidedProject\starter>코드가 실행되면 두 개의 메뉴 항목이 표시됩니다.
- "
1"를 입력하여 "현재 애완동물 정보 모두 나열" 출력을 테스트하세요. - Enter:
2, "작성 중" 메시지 자리 표시자 메시지를 테스트하려면
- "
Enter:
1다음에 "Enter" 키를 눌러 "모든 애완 동물을 표시"합니다.모든 애완 동물 정보가 표시되는지 확인합니다.
모든 애완 동물의 데이터를 관찰할 때 표시된 마지막 애완 동물은 다음 출력과 일치해야 합니다.
ID #: c4 Species: cat Age: 3 Nickname: Lion Physical description: Medium sized, long hair, yellow, female, about 10 pounds. Uses litter box. Personality: A people loving cat that likes to sit on your lap. Press the Enter key to continueEnter 키를 눌러 계속하면 메뉴로 돌아갑니다.
메뉴 프롬프트에서
2을 입력하고 "Enter" 키를 누르십시오.이 선택은 "지정된 특성을 가진 모든 개 표시" 기능을 위한 자리 표시자입니다.
UNDER CONSTRUCTION선택에 대한Display all dogs with a specified characteristic메시지가 표시되는지 확인합니다.다음과 같이 출력됩니다.
UNDER CONSTRUCTION - please check back next month to see progress. Press the Enter key to continue.앱 메뉴에서
exit를 입력하여 프로그램을 종료한 다음 터미널 패널을 닫습니다.프로그램이 종료되어야 합니다.
이제 새 기능 개발을 시작할 준비가 되었습니다.