c# - 用户在数组中搜索项目
问题描述
我目前正在尝试构建一个应用程序,该应用程序将允许用户在数组中选择一个位置,然后在用户选择它们在数组中的位置后将该选择显示回给用户。到目前为止,我的代码是。(在 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# 参考)| 微软文档。
另外,请注意:
数组索引为零:具有
n
元素的数组索引从0
到n-1
。
所以,请考虑添加适当的检查。
这是示例:
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));
推荐阅读
- javascript - 将一种 HTML 结构转换/转换为另一种结构的正确方法是什么?
- javascript - 为什么即使它的反应量不合适,它仍然会放在右舷?不和谐.js
- java - 从目录打开 HTML 文件到 webview Android studio
- python - 本地编辑器上的“ModuleNotFoundError”,但在 Jupyter 中没有
- amazon-web-services - AWS::WAFv2::WebACLAssociation ResourceArn 用于 CloudFormation 中的应用程序负载均衡器
- r - 基于 r 中单元格中字符数的子集数据
- php - 使用 volley 在 android studio 上显示 MySQL 数据的问题
- mysql - 如何根据开始和结束条件之间的值查找行的值?
- vue.js - Vue:试图将 v-model 设置为计算属性?
- discord.py - 设置时间限制来排名 discord.py