我有一个问题是按字母顺序显示名称,反之亦然。当我使用Array.Sort()时,它首先显示最后一个条目,然后按字母顺序排序。任何帮助,建议将受到高度赞赏。以下是我的代码:
static void Main(string[] args)
{
string [] lastName = new string [100];
string inValue = "", moreData = "";
int nameCnt = 0;
while (moreData != "N")
{
lastName[nameCnt] = Convert.ToString(inValue);
nameCnt++;
Console.Write("Enter Last Name: ");
inValue = Console.ReadLine();
Console.Write("Keep going Y/N? ");
moreData = Console.ReadLine();
moreData = moreData.ToUpper();
}
Console.WriteLine();
Console.WriteLine(nameCnt + " Last Name(s) Entered");
Console.WriteLine();
Console.WriteLine("Names in Ascending Order\n");
Array.Sort(lastName);
foreach (string name in lastName)
{
lastName[nameCnt] = Convert.ToString(inValue);
Console.Write(name);
}
Console.WriteLine();
Console.WriteLine("Names in Ascending Order\n");
Array.Reverse(lastName);
foreach (string name in lastName)
{
lastName[nameCnt] = Convert.ToString(inValue);
Console.Write(name);
}
Console.ReadLine();
}
答案 0 :(得分:0)
误解是如果你在foreach中输入变量nameCnt = 4
的四个姓氏
在您的安排的4
位置,您输入您在变量inValue
foreach (string name in lastName)
{
/* Asign position 4 to array inValue input
lastName[nameCnt] = Convert.ToString(inValue); */
Console.WriteLine(name);
}
删除该行并同时订购您的第一行
while (moreData != "N")
{
Console.Write("Enter Last Name: ");
inValue = Console.ReadLine();
lastName[nameCnt] = Convert.ToString(inValue);
nameCnt++;
Console.Write("Keep going Y/N? ");
moreData = Console.ReadLine().ToUpper();
}