我如何确保用户输入必须是相同的输入我需要从我的数组



我是初学者。我有这个问题,我不确定我是否能充分解释它,但让我们看看:

我有一个名为userid的数组和一个名为username的数组。我希望用户给我他/她的id之后,我希望名称用户将类型必须是相同的数组数从用户名数组例如,如果用户输入5,那么他/她的名字必须是"f"否则用户将无法继续。

我不知道该在if语句中输入什么?

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();
if (usernamereply == username[useridreply])
{
}
} 
}

在if条件中忘记添加一个"="。

c#中比较两个值的语法是"=="。那么你的if条件看起来像:

if (usernamereply == username[useridreply])

这里是另一个指向microsoft文档的比较操作符的有用链接:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/comparison-operators

这是另一种方法。在这种方法中:

。检查输入的userid,以验证它是否存在于数组中。我们可以使用for循环,但是c#提供了一个函数。

B。只有当用户id有效时,我们才会请求用户名。这在在线系统中不会发生,但这取决于您。

C。总是使用"=="当测试。一个"=";意味着任务。非常常见的错误。

D。通常使用:userName或userName这样的变量名,当变量名包含多个单词时,至少将第二个单词的第一个字母大写以方便阅读。我没有完全遵循这条规则,我使用了你的一些代码,因为我现在很懒:)

using System;
public class Program
{
public static void Main()
{
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();
//Check if typed userid is in the array or not.
//Note: "001" is not equal to "1" in this test.

int index = Array.IndexOf(userid, userIdReply);
if (index == -1)
{
Console.WriteLine("Error-1:Typed userid not found!");
return;
}

//Now we have a valid userid let's get the user name
Console.Write("please type user name: t");
string userNameReply = Console.ReadLine();

//Note 1-This test is case sensitive.
//user name "A" will not match "a".
//Note 2-C# arrays begin at ZERO not 1.
//if the userid is 4 the corresponding value will be "e" not "d".
if (userNameReply != username[index])
{
Console.WriteLine("Error-2:Typed userid found but username does not match it-Check the case!");
return;
}
}
}

相关内容

最新更新