处理无效输入
本课属于 Coddy Lua 学习旅程的“逻辑与流程”单元。第 47 课,共 54 课。
挑战
简单通过妥善处理无效的菜单命令,完成你的联系人列表应用。当用户输入的命令与任何可用选项都不匹配时,程序应告知用户,并继续运行。
在上一个挑战的基础上,添加一个 else 条件,用来处理不是 add、list、search、delete 或 quit 的命令。这样,当用户输入无法识别的命令时,程序就能给出明确的反馈,提升用户体验。
要求:
- 保留上一个挑战中的所有代码,包括设置、显示菜单、主循环,以及添加、列出、搜索和删除功能
- 添加一个
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逻辑与流程中的所有课
自己练习: Lua 在线编译器