2016-03-16 121 views
0

我想允許用戶輸入用戶名。用戶名應該存儲在一個文件中(如果該文件不存在,則創建該文件)。但是,如果用戶名已存在於文件中,用戶應該會收到錯誤信息。如何讓用戶輸入用戶名?

一旦完成,用戶應該能夠輸入新的用戶名。

我的問題是,我不知道如何繼續詢問用戶名?

string fileName = ("Usernames.txt"); 
if (File.Exists(fileName)) 
    Console.WriteLine("Username file already exists!"); 
else 
    Console.WriteLine("Username file was created!"); 
    FileStream un = new FileStream("Usernames.txt", 
     FileMode.Create, FileAccess.Write); 
    StreamWriter kasutajanimed = new StreamWriter(un); 
    Usernames.Close(); 

Console.WriteLine("Username: "); 
string uCreation = Console.ReadLine(); 
bool exists = false; 
foreach (string lines in File.ReadAllLines("Usernames.txt")) 
{ 
    if (lines == uCreation) 
    { 
     Console.WriteLine("Username already exists!"); 
     exists = true; 
     break; 
    } 
} 
if (!exists) 
{ 
    File.AppendAllText(@"Usernames.txt", uCreation + Environment.NewLine); 
} 
+1

歡迎來到我們的社區。您需要調整您的問題,以便詢問具體問題。告訴我們什麼不起作用,或者哪部分代碼需要幫助。 – jgauffin

+0

是的,但現在我找不到一種方法來繼續使用代碼來請求X事物。否則,謝謝! – CrimzonWeb

回答

0

你只需要另一個循環讓他們輸入另一個用戶名。

while(true) 
{ 
    Console.WriteLine("Username: "); 
    string uCreation = Console.ReadLine(); 
    bool exists = false; 

    foreach (string lines in File.ReadAllLines("Usernames.txt")) 
    { 
     if (lines == uCreation) 
     { 
      Console.WriteLine("Username already exists!"); 
      exists = true; 
      break; 
     } 
    } 

    if (!exists) 
    { 
     File.AppendAllText(@"Usernames.txt", uCreation + Environment.NewLine); 
     break; 
    } 
} 
+0

哇,那很糟糕。這應該是對的。 –

+0

當它詢問一個用戶名時,你輸入一個,它接受它並要求一個新的用戶名,而不是繼續使用該代碼。當你輸入兩次相同的用戶名時,它說用戶名已經存在,然後繼續執行其餘的代碼。 編輯! 你似乎修復它,這似乎適合我!謝謝! :) – CrimzonWeb

+0

@CrimzonWeb由於答案對您有幫助,您應該將其標記爲已接受。考慮加強答案;) – Luaan

0

如果您每次都以這種方式搜索文件,則每個條目都是O(n)。我認爲更好的方法是保留一個包含文件中所有用戶名的集合。因此,在打開文件時,將文件中的所有用戶名添加到HashSet中。然後,您可以直接撥打hashSet.Contains(username)來檢查用戶名是否存在於O(1)時間。

對於不斷詢問用戶,您可以使用一段時間的真循環。像這樣

while (true) // Loop indefinitely 
    { 
     Console.WriteLine("Username: "); // Prompt 
     string line = Console.ReadLine(); // Get string from user 
     if (hashSet.Contains(line)) { 
      Console.WriteLine("Username Already in Use"); 
      continue; 
     } 
     if (line == "exit") // have a way to exit, you can do whatever you want 
     { 
     break; 
     } 
     // Here add to both file and your HashSet... 
    }