【发布时间】:2014-12-06 12:23:02
【问题描述】:
所以我正在为大学制作一个程序,我必须在其中编写一个将名称存储到数组中的程序。 输入新名称时,它将被添加到数组的末尾。用户可以继续添加名称,直到他们输入虚拟值“退出” 完成此操作后,程序将显示任何重复的名称。 例如。 输入姓名:比尔 输入姓名:玛丽 输入姓名:阿尼莎 输入姓名:玛丽 输入名称:退出 玛丽是复制品。
我还应该尝试显示每个名称重复了多少次。
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();
}
这是我的代码,但是当我比较名称时它崩溃了,它给了我一个重复的名称,而没有其他名称。然后崩溃,我认为它与第二个 for 循环有关,但请有人运行它并帮助我。
【问题讨论】:
-
这似乎是它的家庭作业,不是吗?
-
是的,但我需要使用一个数组,它用于大学工作
-
我也想了解数组的工作原理
-
names = new string[i];在这一行,i 是 1。所以字符串数组大小只有 1。那么你可以只访问 0-index。
标签: c# arrays loops variables main