删除联系人
本课属于 Coddy Lua 学习旅程的“逻辑与流程”单元。第 46 课,共 54 课。
挑战
简单为你的联系人列表应用实现删除功能。当用户输入 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逻辑与流程中的所有课
自己练习: Lua 在线编译器