2016-11-04 133 views
2

我有一个小问题添加联系人(姓名和号码)到列表的问题,并在稍后显示它。在添加流程的过程中,我选择了以下方法,用于在添加之前检查用户是否添加了正确的数字格式。如果添加了错误的数字格式,代码会要求他从头开始输入详细信息。我的问题是,如果用户添加了错误的输入,他必须只退一步,即回到添加数字,而不是从头开始。基本上我怎么可以将下面的方法分成两个并使用它们。在这里我已经在一个单独的课程中接触了联系我是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(); 
    } 
} 
+0

你所说的“错误输入”呢?有很多方法可以编写电话号码。你只接受一种特定格式,还是只是检查输入是否可能*是电话号码? – Abion47

+0

'^ \(?([0-9] {3})\)?[ - 。 ]([0-9] {3})[? - 。 ]?([0-9] {4})$'我正在检查此格式@ Abion47 –

回答

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; 
} 
+0

感谢您的答案。帮了很多! –

0

创建函数返回布尔

bool isValidNumber = true; 
do{ 

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

    string NewNumber = Console.ReadLine(); 

    isValidNumber = isValidNumberCheck(NewNumber); 

}while(!isValidNumber);