2016-03-16 122 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... 
    }