将联系人添加到列表

时间:2016-11-04 00:14:16

标签: c#

我有一个小问题声明,即将联系人(姓名和号码)添加到列表中,然后再显示它。在添加过程的过程中,我选择了以下方法,在添加之前检查用户是否添加了正确的数字格式。如果添加了错误的数字格式,代码将要求他从头开始输入详细信息。我的问题是,如果用户添加了错误的输入,他必须只退一步,即返回添加数字,而不是从开始。基本上我怎么能将下面的方法分成两个并使用它们。在这里,我在一个单独的课程中接受了联系。我是c#的初学者。如果有任何错误,请忽略。万分感谢

public void AddingContact()
{
    Contact addContact = new Contact();

    Console.WriteLine("Enter the name to be added:");
    addContact.Name = Console.ReadLine();

    Console.WriteLine("Enter the phone number to be added:");
    string NewNumber = Console.ReadLine();

    if(//So and so condition is true)
    { 
        Add contact to list<contacts>
    }
    else
    {
        AddingContact();
    }
}

2 个答案:

答案 0 :(得分:1)

在获得有效输入之前循环字段的最简单方法是使用do-while块。

public void AddingContact()
{
    Contact addContact = new Contact();

    Console.WriteLine("Enter the name to be added:");
    addContact.Name = Console.ReadLine();

    string NewNumber;
    do 
    {
        NewNumber = Console.ReadLine();
        if (!IsValidPhoneNumber(NewNumber))
        {
            NewNumber = string.Empty;
        }
    } while (string.IsNullOrEmpty(NewNumber));

    Contact.PhoneNumber = NewNumber; // Or whatever the phone number field is
    ContactList.Add(Contact); // Or whatever the contact list is
}

验证电话号码的方法可以写成:

public bool IsValidPhoneNumber(string number)
{
    return Regex.Matches(number, "^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$").Count == 1;
}

答案 1 :(得分:0)

创建函数以验证返回bool的输入数字

bool isValidNumber = true;
do{ 

  Console.WriteLine("Enter the phone number to be added:");

  string NewNumber = Console.ReadLine();

  isValidNumber = isValidNumberCheck(NewNumber);

}while(!isValidNumber);
相关问题