One of the programs I have to write for homework is to make a phonebook.
Write a program that receives some info from the console about people and their phone numbers. You are free to choose the manner in which the data is entered; each entry should have just one name and one number (both of them strings). If you receive a name that already exists in the phonebook, simply update its number. After filling this simple phonebook, upon receiving the command "search", and the command “stop”, your program should be able to perform a search of a contact by name and print her details in format "{name} -> {number}". In case the contact isn't found, print "Contact {name} does not exist."
Here is my code so far:
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);
}
}
}
}
}
I'm getting this at line 27 after I enter a pair in the console:
Unhandled Exception: System.ArgumentException: An item with the same key has alr eady been added.