연락처 삭제하기
Coddy Lua 여정의 Logic & Flow 섹션에 포함된 레슨 — 54개 중 46번째.
챌린지
쉬움연락처 목록 애플리케이션에 삭제 기능을 구현하세요. 사용자가 delete를 입력하면, 프로그램은 이름을 묻고 목록에서 해당 연락처를 찾아 삭제해야 합니다.
이전 챌린지를 바탕으로 delete 명령을 처리하는 기능을 추가하세요. contacts 테이블을 루프하며 일치하는 이름을 가진 연락처를 찾은 다음, table.remove()를 사용하여 목록에서 삭제합니다. 삭제 성공 여부에 대해 사용자에게 피드백을 제공하세요.
요구 사항:
- 이전 챌린지의 모든 코드(설정, 메뉴 표시, 메인 루프, 추가, 목록 및 검색 기능)를 유지합니다.
- 사용자가
delete를 입력하면Enter name to delete:를 출력합니다. io.read()를 사용하여 이름을 읽습니다.ipairs()를 사용하여contacts테이블을 반복합니다.- 각 연락처에 대해
name필드가 삭제할 이름과 정확히 일치하는지 확인합니다. - 일치하는 항목을 찾으면 연락처의 인덱스와 함께
table.remove()를 사용하여 삭제합니다. - 삭제에 성공하면
Contact deleted successfully!를 출력합니다. - 모든 연락처를 확인한 후에도 일치하는 항목이 없으면
Contact not found.를 출력합니다. list명령을 사용했을 때 연락처가 없으면No contacts available.를 출력합니다.add,list,search,quit명령은 이전과 동일하게 작동해야 합니다.
참고: 이 챌린지에서 빈 목록 메시지는 No contacts available.입니다. 이전 레슨에서 다른 문구를 사용했더라도 반드시 이 정확한 문자열을 사용하세요.
상호작용 예시:
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:
list
Contact List:
1. Alice - 555-1234
2. Bob - 555-5678
Enter command:
delete
Enter name to delete:
Alice
Contact deleted successfully!
Enter command:
list
Contact List:
1. Bob - 555-5678
Enter command:
delete
Enter name to delete:
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 available.")
else
print("Contact List:")
for i, contact in ipairs(contacts) do
print(i .. ". " .. contact.name .. " - " .. contact.phone)
end
end
print()
elseif command == "search" then
print("Enter name to search:")
local searchName = io.read()
local found = false
for i, contact in ipairs(contacts) do
if contact.name == searchName then
print("Found: " .. contact.name .. " - " .. contact.phone)
found = true
break
end
end
if not found then
print("Contact not found.")
end
print()
elseif command == "quit" then
print("Goodbye!")
break
else
print("Command not yet implemented")
print()
end
end