Menu
CoddyTech

搜索联系人

本课属于 Coddy Lua 学习旅程的“逻辑与流程”单元。第 45 课,共 54 课。

challenge icon

挑战

简单

为你的联系人列表应用实现搜索功能。当用户输入 search 时,程序应提示用户输入姓名,并显示所有匹配的联系人。

在上一个挑战的基础上,添加处理 search 命令的功能。遍历 contacts 表,查找姓名与搜索词匹配的联系人。显示所有匹配项;如果没有找到联系人,则告知用户。

要求:

  • 保留上一个挑战中的所有代码(设置、显示菜单、主循环、添加功能和列表功能)
  • 当用户输入 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

逻辑与流程中的所有课

自己练习: Lua 在线编译器