首页 > 解决方案 > 用户在数组中搜索项目

问题描述

我目前正在尝试构建一个应用程序,该应用程序将允许用户在数组中选择一个位置,然后在用户选择它们在数组中的位置后将该选择显示回给用户。到目前为止,我的代码是。(在 C# 中)

// 字符串数组

    string[] nameArray = new string[] { "Tyler", "Kyle", "Roger", "Rick" };

    Console.WriteLine("Select an item from the array using numbers 0-3");
    string userSelection = Console.ReadLine();
    int arraySelection1 = Convert.ToInt32(userSelection);
    Console.WriteLine("You have choosen " + arraySelection1);

标签: c#.net

解决方案


您要求的不是搜索,而是直接数组访问 - 通过元素索引。为此,请考虑使用[] 运算符(C# 参考)| 微软文档

另外,请注意:

数组索引为零:具有n元素的数组索引从0n-1

数组(C# 编程指南)| 微软文档

所以,请考虑添加适当的检查。

这是示例:

string[] nameArray = new string[] { "Tyler", "Kyle", "Roger", "Rick" };

// Input.
Console.WriteLine(String.Format("Select an item from the array using numbers {0}-{1}", 0, nameArray.Length));
string selectedIndexString = Console.ReadLine();

// Processing.
int selectedIndex = Convert.ToInt32(selectedIndexString);
if (selectedIndex < 0 || selectedIndex >= nameArray.Length)
{
    throw new ArgumentException(String.Format("The index must belong to the range: [{0}:{1}]", 0, nameArray.Length));
}
string selectedString = nameArray[selectedIndex];

// Output.
Console.WriteLine(String.Format("You have choosen: {0}", selectedString));

推荐阅读