3 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
請(qǐng)注意,電話號(hào)碼不是整數(shù),而是字符串。它可能以零開頭,如果您將其解析為 int,則會(huì)丟失前導(dǎo)零(0123456789 變?yōu)?123456789)。另外,我認(rèn)為“+31 (0)6-12345678”是一個(gè)有效的電話號(hào)碼。
這是一個(gè)可以完成您想要的操作的示例。它會(huì)不斷請(qǐng)求輸入,直到用戶輸入“exit”并用電話號(hào)碼更新姓名。
public static void Main()
{
var directory = new Dictionary<string, string>();
// Keep requesting inputs
while (true)
{
string input = Console.ReadLine();
// provide a possibility to break the loop.
if (input == "exit")
{
break;
}
string[] items = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (items.Length != 2)
{
Console.WriteLine("Expecting '{Name} {Phonenumber}'");
continue;
}
directory[items[0]] = items[1];
}
// TODO: Do something with directory
}

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用 String.Split() 分割行,即
var pair = Console.ReadLine().Split(' ');
Dictionary.Add(pair[0], int.Parse(pair[1]))

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊
static void Main(string[] args)
{
Dictionary<string, int> Directory = new Dictionary<string, int>();
Console.WriteLine("Enter the Number of inputs");
int count = int.Parse(Console.ReadLine());
for (int i = 0; i < count; i++)
{
Console.WriteLine("Enter the Name " + i + 1 + " : ");
string Name = Console.ReadLine();
Console.WriteLine("Enter the Age " + i + 1 + " : ");
int Age = Convert.ToInt32(Console.ReadLine());
Directory.Add(Name, Age);
}
Console.WriteLine("Press key to display the contents of your dictionary..");
Console.ReadLine();
foreach (var item in Directory)
{
Console.WriteLine("Name : " + item.Key);
Console.WriteLine("Age : " + item.Value);
}
Console.ReadLine();
}
- 3 回答
- 0 關(guān)注
- 153 瀏覽
添加回答
舉報(bào)