我是初學者。我有這個問題我不確定我是否能夠充分解釋它但讓我們看看:
我有一個名為 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])
{
}
}
}
uj5u.com熱心網友回復:
在您的 if 條件中,您忘記再添加一個“=”。
在 C# 中,比較兩個值的語法是“==”。
所以你的 if 條件看起來像:
if (usernamereply == username[useridreply])
這是比較運算子的 Microsoft 檔案的另一個有用鏈接:https ://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/comparison-operators
uj5u.com熱心網友回復:
這是另一種方法。在這種方法中:
A. 檢查輸入的 userid 以驗證它存在于陣列中。我們可以為此使用 for 回圈,但 C# 提供了一個函式。
B. 只有當 userid 有效時,我們才要求提供用戶名。這不會發生在在線系統中,但這取決于您。
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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537923.html
標籤:C#数组细绳if语句
