Reputation: 47
So im making a program for college in which i must Write a program that will store names into an array. As a new name is entered it will be added to the end of the array. The user can keep adding names until they enter the dummy val-ue ‘exit’ Once this has been done the program will display any duplicate names. E.g. Enter name: Bill Enter name: Mary Enter name: Anisha Enter name: Mary Enter name: exit Mary is a duplicate.
I should also try to show how many times each name was duplicated.
static void Main(string[] args)
{
Console.WriteLine("This program allows you to write names to a list,");
int i = 0;
//Due to the fact than i cannont resize an array after initialization, i used a list and converted it to an array at a later point
List<string> names = new List<string>();
string name = " ";
Console.WriteLine("Enter names then press enter to add them to the list of names! if you wish to exit simple type exit.");
//This loop adds names to the list
while (name.ToLower() != "exit")
{
Console.WriteLine("Enter Name: ");
name = Console.ReadLine();
names.Add(name);
i++;
}
//This line converts the list to an array
string[] nameArray = names.ToArray();
for(int z = 0;z <nameArray.Length + 1;z++)
{
for (int y = 0; y < z ; y++)
{
if (nameArray[y] == nameArray[z])
{
Console.WriteLine("The name: " + nameArray[y] + " is a duplicate.");
}
else
{
Console.Write(" ");
}
}
}
Console.ReadLine();
}
This is my code but it crashes when I compare the names, it gives me one duplicate name and no others. and then crashes, i think it is relative to the second for loop but please could someone run this and help me out.
Upvotes: 0
Views: 2342
Reputation: 11478
Program is incorrect, in fact this is a case for exception, since your initial value for i is 1 and your string [] is of size 1 so at most you can access index 0, in fact in the first loop itself you are trying index 1, which is out of range exception. Even if you correct that the logic is incorrect, the way it has been designed. Following is a better solution
static void Main(string[] args)
{
Console.WriteLine("This program allows you to write names to a list,");:
List<string> nameList = new List<string>();
string name = " ";
Console.WriteLine("Enter names then press enter to add them to the list of names! if you wish to exit simple type exit.");
while (name.ToLower() != "exit")
{
Console.WriteLine("Enter Name: ");
name = Console.ReadLine();
nameList.Add(name);
}
string[] nameArray = nameList.ToArray();
Console.ReadLine();
}
nameArray will be the array that you need as a response
Upvotes: 1
Reputation: 12449
An array can not be resized after initialization. You'll have to use List
instead of an array.
If you only want to use array, then you will have to fix its size at the time of initialization. You can ask the user to enter the array size. Or you can initialize a long length array (but its not recommended).
Upvotes: 1