如何验证用户输入的用户名与指定ID对应的数组元素一致?
问题解决:验证用户ID与对应用户名匹配
你的核心问题是直接用字符串类型的输入ID作为数组索引,这在C#里是不允许的——数组索引必须是整数类型。正确的逻辑应该是先找到输入ID在userid数组中的位置,再用这个位置去username数组中匹配对应的值。
修正步骤:
- 第一步:用
Array.IndexOf找到输入ID在userid数组中的索引 - 第二步:判断索引是否有效(避免用户输入不存在的ID)
- 第三步:用有效索引取出对应用户名,和用户输入的用户名做对比
修正后的完整代码
class Program { static void Main(string[] args) { string[] userid = {"0" , "1" , "2" , "3" , "4" , "5"}; string[] username = { "a" , "b" , "c" , "d" , "e" , "f"}; Console.Write("please type user id: \t"); string useridreply= Console.ReadLine(); Console.Write("please type user name: \t"); string usernamereply = Console.ReadLine(); // 找到输入ID在数组中的索引位置 int idIndex = Array.IndexOf(userid, useridreply); // 先判断ID是否存在 if (idIndex == -1) { Console.WriteLine("Invalid user ID!"); return; // 终止程序,避免后续错误 } // 验证用户名是否匹配对应索引的内容 if (usernamereply == username[idIndex]) { Console.WriteLine("Verification passed! You can proceed."); // 这里写验证通过后的操作逻辑 } else { Console.WriteLine("Username does not match the ID!"); } } }
关键细节说明:
Array.IndexOf(userid, useridreply):遍历userid数组,返回第一个匹配元素的索引;如果没找到,返回-1- 先判断索引是否为
-1:防止用户输入不存在的ID导致后续数组访问报错 - 字符串比较
==在C#中对值类型字符串是直接比较内容的,这里可以直接使用
内容的提问来源于stack exchange,提问作者Shazil
相关产品推荐
相关产品推荐

