-4
我有寫家庭作業的程序是使電話簿。C# - 簡單的電話簿功課
編寫一個程序,該程序從控制檯接收關於人員及其電話號碼的一些信息。 您可以自由選擇輸入數據的方式;每個條目應該只有一個名字和一個數字(都是字符串)。如果您收到電話簿中已存在的名稱,只需更新其號碼即可。 填補這個簡單的電話簿,在接到指令後「搜索」,並命令「停止」,你的程序應該能夠執行按姓名搜索聯繫人,並在格式打印她的細節「{名稱} - > {數}」。如果未找到聯繫人,請打印「聯繫人{姓名}」不存在。「
這是到目前爲止我的代碼:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Phonebook
{
static void Main()
{
string[] input = new string[100];
input[1] = string.Empty;
var dict = new Dictionary<string, string>();
while (input[0] != "search")
{
input = Console.ReadLine().Split('-');
for (int i = 0; i < input.Length; i++)
{
if (dict.ContainsKey(input[i]))
{
dict.Remove(input[i]);
}
dict.Add(input[0],input[1]);
}
}
while (input[0] != "stop")
{
input = Console.ReadLine().Split();
}
for (int i = 0; i < input.Length - 1; i++)
{
foreach (KeyValuePair<string, string> c in dict)
{
if (input[i] == c.Key)
{
Console.WriteLine("{0} -> {1}", c.Key, c.Value);
}
else
{
Console.WriteLine("Contact {0} does not exist.", c.Key);
}
}
}
}
}
我在控制檯輸入一組後,我在第27行得到這個:
未處理的異常信息:System.ArgumentException:一個具有相同密鑰的項目已添加alr 。
無論線27,在運行時你試圖將元素添加到已經包含給定鍵的元素的字典。正如錯誤告訴你的那樣,你不能那樣做。這是一個很好的機會,可以逐步調試調試器中的代碼,並確定實際發生的情況以及爲什麼您認爲它應該不同。 – David
簡單的谷歌搜索返回多個重複。 – Sayse
那個非常具有描述性的錯誤信息,你不理解嗎? – Jamiec