You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何验证用户输入的用户名与指定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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:25:21