I am a beginner. I have this problem I am not sure if I will be able to explain it adequately but let's see:
I have an array called userid and another array called username. I want the user to give me his/her id after that I wish that the name user will type has to be the same array number from the username array for example if the user types 5 then his/her name must be "f" otherwise user can't go any further.
I don't know what to type in if statement?
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])
{
}
}
}
CodePudding user response:
in your if-condition you forgot to add one more "=".
In C# the syntax for comparing two values is "==".
So your if-condition would look like:
if (usernamereply == username[useridreply])
Here is another helpful link to the microsoft documentation for the comparison operators: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/comparison-operators
CodePudding user response:
Here is another approach. In this approach:
A. The userid entered is checked to verify it exists in the array. We can use a for loop for that but C# offers a function.
B. Only when the userid is valid we ask for the username. This does not happen in online systems, but its up to you.
C. Always use "==" when testing. One "=" means assignment. Very common error.
D. It is common to use variable names such as: userName or UserName, when the variable name has more than one word, at least make the second word's first letter in upper case for ease of reading. I did not follow this rule thoroughly, I used some of your code as is because I am lazy now :)
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;
}
}
}