gpt4 book ai didi

c# - 将联系人添加到列表

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:23 25 4
gpt4 key购买 nike

我有一个小问题陈述,就是将联系人(姓名和号码)添加到列表中,然后再显示它。在添加过程中,我选择了以下方法,它在添加之前检查用户是否添加了正确的数字格式。如果添加了错误的数字格式,代码将要求他从头开始输入详细信息。我的问题是,如果用户添加了错误的输入,他只需要后退一步,即回到添加数字而不是从头开始。基本上我怎样才能将下面的方法分成两部分并使用它们。在这里,我在单独的类(class)中学习了接触。我是 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();
}
}

最佳答案

循环一个字段直到获得有效输入的最简单方法是使用 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
}

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

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

关于c# - 将联系人添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40413354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com