연락처 검색하기
Coddy Lua 여정의 Logic & Flow 섹션에 포함된 레슨 — 54개 중 45번째.
챌린지
쉬움연락처 관리 애플리케이션을 위한 검색 기능을 구현하세요. 사용자가 search를 입력하면, 프로그램은 이름을 묻는 메시지를 표시하고 일치하는 모든 연락처를 보여주어야 합니다.
이전 챌린지를 바탕으로, search 명령을 처리하는 기능을 추가하세요. contacts 테이블을 루프(loop)하며 검색어와 이름이 일치하는 연락처를 찾습니다. 일치하는 모든 항목을 표시하거나, 연락처를 찾을 수 없는 경우 사용자에게 알립니다.
요구 사항:
- 이전 챌린지의 모든 코드(설정, 메뉴 표시, 메인 루프, 추가 기능, 목록 기능)를 유지합니다.
- 사용자가
search를 입력하면,Enter name to search:를 출력합니다. io.read()를 사용하여 검색어를 읽습니다.ipairs()를 사용하여contacts테이블을 반복합니다.- 각 연락처에 대해
name필드가 검색어와 정확히 일치하는지 확인합니다. - 일치하는 항목을 찾으면
Found: [name] - [phone]형식으로 출력합니다. - 모든 연락처를 확인한 후에도 일치하는 항목이 없으면
Contact not found.를 출력합니다. add,list,quit명령은 이전과 동일하게 작동해야 합니다.- 기타 명령은 여전히
Command not yet implemented를 출력해야 합니다.
상호작용 예시:
Welcome to Contact List Manager!
Available Commands:
add - Add a new contact
list - Display all contacts
search - Search for a contact
delete - Delete a contact
quit - Exit the program
Enter command:
add
Enter name:
Alice
Enter phone number:
555-1234
Contact added successfully!
Enter command:
add
Enter name:
Bob
Enter phone number:
555-5678
Contact added successfully!
Enter command:
search
Enter name to search:
Alice
Found: Alice - 555-1234
Enter command:
search
Enter name to search:
Charlie
Contact not found.
Enter command:
quit
Goodbye!직접 해보기
-- Contact List Manager
local contacts = {}
-- Display welcome message
print("Welcome to Contact List Manager!")
print()
-- Display menu
print("Available Commands:")
print("add - Add a new contact")
print("list - Display all contacts")
print("search - Search for a contact")
print("delete - Delete a contact")
print("quit - Exit the program")
print()
-- Main loop
while true do
print("Enter command:")
local command = io.read()
if command == "add" then
print("Enter name:")
local name = io.read()
print("Enter phone number:")
local phone = io.read()
table.insert(contacts, {name = name, phone = phone})
print("Contact added successfully!")
print()
elseif command == "list" then
if #contacts == 0 then
print("No contacts found.")
else
print("Contact List:")
for i, contact in ipairs(contacts) do
print(i .. ". " .. contact.name .. " - " .. contact.phone)
end
end
print()
elseif command == "quit" then
print("Goodbye!")
break
else
print("Command not yet implemented")
print()
end
end