Skip to main content
 首页 » 编程设计

c#之与索引比较查找数组中的值

2024年08月06日32txw1958

我正在自学 C#,遇到一个问题时遇到了困难。 我需要根据用户的输入找到数组的值。

string[] arr = new string[6]; 
            arr[0] = "Us"; 
            arr[1] = "Canada"; 
            arr[2] = "Uk"; 
            arr[3] = "China"; 
            arr[4] = "India"; 
            arr[5] = "Korea"; 
 
Console.WriteLine("Choose a Country (or -1 to quit):"); 

现在,如果用户输入 3,它将选择中国。

我很困惑如何将用户输入与索引进行比较并获得该值。

我试过了,但似乎不起作用:(

int number = Convert.ToInt32(Console.ReadLine()); 
int arrayindex = Array.IndexOf(arr,number); 

请您参考如下方法:

I am confused how to compare user input with index and get that value

您可以使用索引器获取您拥有的数组的特定索引处的值。

int number = Convert.ToInt32(Console.ReadLine()); 
string country = arr[number]; // This will give you China 

如果你想确保用户给出的数字是有效的数组索引,那么你可以在使用索引器之前应用条件,它应该是 0 或比数组长度少一。

if(number > -1 && number < arr.Length) 
     country = arr[number];