ananth reddy ananth reddy - 1 month ago 6
C# Question

Adding a contact to a list

I have a small problem statement of adding contacts(Name and Number) to a list and later displaying it. In the process of adding the process I have chosen is following method where it checks if the user has added the right format of number or not before adding. If a wrong format of number is added, the code will ask him to enter the details from beginning. My problem is if user has added wrong input he has to go only one step back i.e back to adding number and not from beginning. Basically how can i separate the below method into two and use them. Here i have taken Contact in a separate class. Am a beginner in c#. Please ignore if there are any errors. Thanks a ton

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();
}
}

Answer

The simplest way to loop on a field until you get valid input is by using a do-while block.

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
}

The method for validating the phone number can be written as such:

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