class Program
{
static void Main(string[] args)
{
int[] search = { 88, 62, 5, 18, 22, 78, 13, 8, 33, 7 };
Console.WriteLine("Enter value to find");
int val = int.Parse(Console.ReadLine());
int place = -1;
for (int i = 0; i<10; i++)
{
if (search[i]== val)
{
place = i +1;
}
}
if(place == -1)
{
Console.WriteLine("The Target Value was not found in the list");
Console.ReadLine();
}
else
{
Console.WriteLine("The Target Value was found at location: " + place);
Console.ReadLine();
}
}
}
}
我试图搜索在数组中输入的值,我得到了工作,现在我想使它成为一个方法/函数,但我不知道如何。
那么,让我们开始提取方法。我们可以从用户输入开始:
private static int ReadInteger(string prompt) {
while (true) {
if (!string.IsNullOrWhitespace(prompt))
Console.WriteLine(prompt);
// What if user put "bla-bla-bla"? That's why we TryParse (not Parse)
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value. Please, try again.");
}
}
然后继续FindIndex
// Let's put IEnumerable<int> which allows not only array, but list, hashset etc.
private static int FindIndex(IEnumerable<int> values, int toFind) {
if (values == null)
return -1;
int index = 0;
foreach (int value in values) {
index += 1;
if (value == toFind)
return index;
}
return -1;
}
最后,我们从Main
中调用它们:
static void Main(string[] args) {
int[] search = { 88, 62, 5, 18, 22, 78, 13, 8, 33, 7 };
int place = FindIndex(search, ReadInteger("Enter value to find"));
Console.WriteLine(place >= 0
? $"The Target Value was found at location: {place}"
: "The Target Value was not found in the list"
);
Console.ReadLine();
}