代码做了我想要的,但我想进一步。目前,如果用户输入错误的名称,它将输出"作者未找到"然后结束。
如何让它重新输入代码?
static void Main(string[] args)
{
string[] author = {"William Shakespear", "Mark Twain", "Jane Austin", "Charlotte Bronte", "Louisa May Alcott",
"Lewis Carroll", "D.H. Lawrence", "Charles Dickens", "Lucy Maud Montgomery", "Alexander Dumas" };
Console.WriteLine("Please type in an Author: ");
string name = Console.ReadLine();
int location = linearUnsorted(author, name);
if (location == -1)
{
Console.WriteLine("Author not found, please try another");
}
else
{
Console.WriteLine("{0} is located at {1} in the poll", name, location + 1);
}
Console.ReadLine();
}
public static int linearUnsorted(string[] arr, string item)
{
int location = 0;
while (location <arr.Length && !String.Equals(item, arr[location], StringComparison.OrdinalIgnoreCase))
{
location++;
}
if (location == arr.Length)
{
location = -1;
}
return location;
}
}
}
答案 0 :(得分:3)
你应该把你的逻辑放在循环中并继续直到输入无效:
static void Main(string[] args)
{
string[] author = {"William Shakespear", "Mark Twain", "Jane Austin", "Charlotte Bronte", "Louisa May Alcott",
"Lewis Carroll", "D.H. Lawrence", "Charles Dickens", "Lucy Maud Montgomery", "Alexander Dumas" };
while (true)
{
Console.WriteLine("Please type in an Author: ");
string name = Console.ReadLine();
int location = linearUnsorted(author, name);
if (location == -1)
{
Console.WriteLine("Author not found, please try another");
}
else
{
Console.WriteLine("{0} is located at {1} in the poll", name, location + 1);
break;
}
}
Console.ReadLine();
}
答案 1 :(得分:1)
你可以用while循环来完成。
Console.WriteLine("Please type in an Author: ");
int location;
while(location = linearUnsorted(author, Console.Readline()) == -1)
{
Console.WriteLine("Author not found, please try another: ");
}
Console.WriteLine("{0} is located at {1} in the poll", name, location + 1);
P.S你应该使用int index = Array.IndexOf(author, name);
来获取数组中的项目索引,如果你想要不区分大小写的检查,可以使用Array.FindIndex(author, t => t.Equals(name, StringComparison.InvariantCultureIgnoreCase))
。