잘못된 입력 처리하기
Coddy Lua 여정의 Logic & Flow 섹션에 포함된 레슨 — 54개 중 47번째.
챌린지
쉬움잘못된 메뉴 명령에 대한 적절한 처리를 추가하여 연락처 관리 애플리케이션을 완성하세요. 사용자가 사용 가능한 옵션 중 어느 것과도 일치하지 않는 명령을 입력하면, 프로그램은 이를 사용자에게 알리고 계속 실행되어야 합니다.
이전 챌린지를 바탕으로, add, list, search, delete, 또는 quit이 아닌 모든 명령을 처리하기 위한 else 조건을 추가하세요. 이는 인식되지 않는 명령이 입력되었을 때 명확한 피드백을 제공함으로써 사용자 경험을 향상시킵니다.
요구 사항:
- 이전 챌린지의 모든 코드(설정, 메뉴 표시, 메인 루프, add, list, search, delete 기능)를 유지합니다.
- 유효한 옵션과 일치하지 않는 모든 명령을 처리하기 위해
else조건을 추가합니다. - 잘못된 명령이 입력되면
Invalid command. Please try again.을 출력합니다. - 잘못된 명령 메시지를 표시한 후에도 프로그램은 계속 실행되어야 합니다.
- 기존의 모든 명령(
add,list,search,delete,quit)은 이전과 동일하게 작동해야 합니다.
상호작용 예시:
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:
show
Invalid command. Please try again.
Enter command:
remove
Invalid command. Please try again.
Enter command:
list
Contact List:
1. Alice - 555-1234
Enter command:
help
Invalid command. Please try again.
Enter command:
quit
Goodbye!직접 해보기
-- Contact List Manager with Delete Functionality
local contacts = {}
print("Welcome to Contact List Manager!")
print()
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()
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()
local contact = {name = name, phone = phone}
table.insert(contacts, contact)
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 == "delete" then
print("Enter name to delete:")
local deleteName = io.read()
local found = false
for i, contact in ipairs(contacts) do
if contact.name == deleteName then
table.remove(contacts, i)
print("Contact deleted successfully!")
found = true
break
end
end
if not found then
print("Contact not found.")
end
print()
elseif command == "quit" then
print("Goodbye!")
break
end
end