I am trying to teach myself C#. I spent about ten hours trying to find a solution and could not come up with a working one. So I am trying this from a different approach. I got the answer and I am going to work my way back to the start. I have added comment to show my line of thinking.
// TestContacts.cs
using System;
public class TestContacts
{
public static void Main()
{
string[] names = new string[10];
int count = 0; // what is var for? My first thought was it placed the new entry in the next available spot but should that happen anyway?
int index;
string target;
names[count++] = "Tom";
names[count++] = "Dick";
names[count++] = "Harry";
InputWrapper iw = new InputWrapper();
Console.WriteLine("Enter command, quit to exit");
string cmd = iw.getString("> ");
while (! cmd.Equals("quit"))
{
switch (cmd)
{
case "add":
string name = iw.getString("name: ");
names[count++] = name; //This why I think count determines place in the array
break;
case "forward":
for (int i = 0; i < count; i++) // is this i only avaiable in this case? I think it has to be
Console.WriteLine(names[i]);
break;
case "reverse":
for (int i = count - 1; i >= 0; i--)
Console.WriteLine(names[i]);
break;
case "find":
target = iw.getString("target name: ");
index = Search(names, count, target); // Is this a call to the search method at the bottom?
if (index != -1)
Console.WriteLine("{0} found at {1}", target, index);
else
Console.WriteLine("{0} not found", target);
break;
case "remove":
target = iw.getString("remove name: ");
index = Search(names, count, target);
if (index != -1)
{
// Move names to fill hole
for (int i = index; i < count - 1; i++)
names[i] = names[i + 1];
count--;
Console.WriteLine("{0} has been removed", target);
}
else
Console.WriteLine("{0} not found", target);
break;
default:
Console.WriteLine("The following commands are available:");
Console.WriteLine(" add add a contact");
Console.WriteLine(" forward show contacts in forward order");
Console.WriteLine(" reverse show contacts in reverse order");
Console.WriteLine(" find find a contact");
Console.WriteLine(" remove remove a contact");
Console.WriteLine(" quit exit the program");
break;
}
cmd = iw.getString("> ");
}
}
public static int Search(string[] array, int count, string target)
{
int i = 0;
bool found = false;
while (!found && i < count)
{
if (target == array[i])
found = true;
else
i++;
}
if (found)
return i;
else
return -1;
}
}