C # сохранение и извлечение данных в текстовом файле ... Когда опция выбрана, данные удваиваются - PullRequest
0 голосов
/ 15 января 2019

Итак, я делаю школьное задание, где пользователю предлагается 3 варианта. -Register - где пользователь регистрируется, и экземпляр его свойств сохраняется в списке, а затем сохраняется в текстовом файле.

-Login - пользователь вводит имя пользователя и пароль, и после их проверки пользователь входит в другое меню. В меню есть опция, где пользователь может купить кофе. При покупке кофе начисляется балл за кофе. Имейте в виду, что у пользователей есть свойство, называемое «точки кофе», которое увеличивается на 1 каждый раз, когда он покупает кофе. Я не буду описывать другие варианты, так как они не важны.

-Выход- просто выход.

Итак, код для получения текущих данных текстового файла:

public static List<string> textLines = new List<string>();

textLines = File.ReadAllLines("Customer.txt").ToList();
    foreach (string userData in textLines)
    {
        //Extract a new Customer object from each userData
        Customer c = new Customer();
        string[] customerData = userData.Split('^');
        c.iName = customerData[0];
        c.iSurname = customerData[1];
        c.iID = customerData[2];
        c.iEmail = customerData[3];
        c.iHomeAddress = customerData[4];
        c.iMobile = Convert.ToInt32(customerData[5]);
        c.iUsername = customerData[6];
        c.iPassword = customerData[7];
        c.iCoffeePoints = Convert.ToInt32(customerData[8]);

        //Add customer object to customer list
        customerList.Add(c);

     }

Код для регистрации:

public static void RegisterCust() //Asking the customer for his/her 
registration information
{
    Customer c = new Customer();
    Console.Write("\nName: ");
    c.iName = Console.ReadLine();

    Console.Write("Surname: ");
    c.iSurname = Console.ReadLine();

    Console.Write("ID: ");
    c.iID = Console.ReadLine();

    Console.Write("Email Address: ");
    c.iEmail = Console.ReadLine();

    Console.Write("Home Address: ");
    c.iHomeAddress = Console.ReadLine();

    Console.Write("Mobile Number: ");
    c.iMobile = Convert.ToInt32(Console.ReadLine());

    Console.Write("Username: ");
    c.iUsername = Console.ReadLine();
    Console.Write("Password: ");
    c.iPassword = Console.ReadLine();

    c.iCoffeePoints = 0;

    //Checking if the customer username already exists in the textfile
    bool usernameCheck = (from custUser in customerList
                         where custUser.iUsername == c.iUsername
                         select custUser).Any();

    //Checking if the customer email already exists in the textfile
    bool emailCheck = (from custUser in customerList
                      where custUser.iEmail == c.iEmail
                      select custUser).Any();

    //Checking if the customer ID already exists in the textfile
    bool idCheck = (from custUser in customerList
                   where custUser.iID == c.iID
                   select custUser).Any();

    bool bariUsernameCheck = (from bariUser in baristaList
                   where bariUser.iUsername == c.iUsername
                   select bariUser).Any();

    bool bariEmailCheck = (from bariUser in baristaList
                   where bariUser.iEmail == c.iEmail
                   select bariUser).Any();

    bool bariIDCheck = (from bariUser in baristaList
                   where bariUser.iID == c.iID
                   select bariUser).Any();

    /*If bool userNameCheck = true, 
        bool emailCheck = true
        bool idCheck = true, 
        meaning there already is that username, email or ID in the 
        textfile, then print the error message and call RegisterCust()*/
    if (usernameCheck || bariUsernameCheck) 
    {
        Console.WriteLine("Username already in use. Please input the data again.");
        RegisterCust();
    }
    else if (emailCheck || bariEmailCheck)
    {
        Console.WriteLine("Email already in use. Please input the data again.");
        RegisterCust();
    }
    else if (idCheck || bariIDCheck)
    {
        Console.WriteLine("ID already in use. Please input the data again.");
        RegisterCust();
    }
    else //else, if every property is unique, then add the customer into the customerList
    {
        customerList.Add(c);
        Console.WriteLine("\nRegistered!");
        Console.WriteLine();
        System.Threading.Thread.Sleep(1000); //Program waits for 1 second
        Console.Clear();
        CustomerSaveToTxt();
        Main(null);
        }
    }

Код для входа:

public static void customerLogin()
{
    Console.WriteLine("\nUsername");
    cu2.iUsername = Console.ReadLine();
    Console.WriteLine("Password");
    cu2.iPassword = Console.ReadLine();

    bool usernameLoginCheck = (from custUser in customerList
                              where custUser.iUsername == cu2.iUsername
                              select custUser).Any();

    bool passwordLoginCheck = (from custUser in customerList
                              where custUser.iPassword == cu2.iPassword
                              select custUser).Any();

    bool userOrBari = (from custUser in customerList
                              where custUser.iPassword == cu2.iPassword && custUser.iUsername == cu2.iUsername
                              select custUser).Any();

    bool bariUsernameCheck = (from custUser in baristaList
                             where custUser.iUsername == cu2.iUsername
                             select custUser).Any();

    bool bariPasswordCheck = (from custUser in baristaList
                             where custUser.iPassword == cu2.iPassword
                             select custUser).Any();

    bool userOrBari2 = (from custUser in baristaList
                       where custUser.iPassword == cu2.iPassword && custUser.iUsername == cu2.iUsername
                       select custUser).Any();


    if (usernameLoginCheck && passwordLoginCheck && userOrBari)
    {
        menuUser();
    }
    else if (bariUsernameCheck && bariPasswordCheck && userOrBari2)
    {

        baristaLoggedIn();
    }
    else
    {
        Console.WriteLine("Wrong username or password. Input them again please.");
        customerLogin();
    }

} 

Код для сохранения элементов в списке в текстовый файл:

public static void CustomerSaveToTxt() //this method saves all the data inputted in the customer textfile
{
    foreach (Customer Customer in customerList)
    {
        customerOutput.Add(Customer.iName + "^" + Customer.iSurname + "^" + Customer.iID + "^" + Customer.iEmail + "^" + Customer.iHomeAddress + "^" + Customer.iMobile + "^" + Customer.iUsername + "^" + Customer.iPassword +"^"+Customer.iCoffeePoints);
     }
        File.WriteAllLines("customer.txt", customerOutput);

}

Код для покупки кофе и увеличения точки кофе:

Coffee method = new Coffee();
    //Call the method "PerparingCoffee();"
    method.PreparingCoffee();
    System.Threading.Thread.Sleep(2000);
    Console.WriteLine();
    Console.WriteLine("Coffee done! 1 point added to your coffee points!");

    //First I get the customer from customerList with a username = to the username entered to login.
    var cp = from custUser in customerList
                  where custUser.iUsername == cu2.iUsername
                 select custUser;

   string nName = "";
   string nSurname = "";
   string nID = "";
   string nEmail = "";
   string nHomeAddress = "";
   int nMobile = 0;
   string nUsername = "";
   string nPassword = "";
   int nCoffeePoints = 0;
   //I used the variables above to store the user's properties inside them, however coffee points increments by 1
   foreach (Customer s in cp)
   {
       nName = s.iName;
       nSurname = s.iSurname;
       nID = s.iID;
       nEmail = s.iEmail;
       nHomeAddress = s.iHomeAddress;
       nMobile = s.iMobile;
       nUsername = s.iUsername;
       nPassword = s.iPassword;
       nCoffeePoints = s.iCoffeePoints + 1;
   }

   //I created a new instance with the variables holding the information
   Customer c6 = new Customer();
   c6.iName = nName;
   c6.iSurname = nSurname;
   c6.iID = nID;
   c6.iEmail = nEmail;
   c6.iHomeAddress = nHomeAddress;
   c6.iMobile = nMobile;
   c6.iUsername = nUsername;
   c6.iPassword = nPassword;
   c6.iCoffeePoints = nCoffeePoints;


   customerList.RemoveAll(x => x.iUsername == cu2.iUsername && x.iCoffeePoints == nCoffeePoints - 1);
   customerList.Add(c6);
   CustomerSaveToTxt();

Теперь, когда я запускаю программу и регистрируюсь, пользователь правильно сохраняется в текстовом файле. Кроме того, не закрывая консольное приложение, когда я нажимаю «Войти» и покупаю кофе, оно дублирует содержимое текстового файла. Это означает, что если до регистрации у меня было 4 пользователя, сохраненных в текстовом файле: пользователи A, B, C, D, при регистрации и переходе непосредственно к входу в систему и покупке кофе, мой текстовый файл выглядел бы так: A, B, C , D, A, B, C, D, E, где E - новый пользователь. Однако, если я запущу программу, зарегистрируюсь, затем закрою консольное приложение, снова запустю его, войду в систему и куплю кофе, это будет работать отлично. Это означает, что мой текстовый файл будет выглядеть так: A, B, C, D, E. Это действительно раздражающая проблема, которую я не знаю, как ее исправить. Помощь будет очень признателен!

Спасибо!

*** EDIT: я исправил проблему, сначала очистив customerList прямо перед тем, как получить клиентов из текстового файла, и я очистил список customerOutput в методе customerToTxt. Спасибо всем, кто помог !!

1 Ответ

0 голосов
/ 15 января 2019

Проблема в том, что вы не очищаете список перед его использованием. Поэтому перепишите эту часть кода следующим образом

 public static void CustomerSaveToTxt() //this method saves all the data inputted in the customer textfile
  { 
        customerOutput.clear();
        foreach (Customer Customer in customerList){
            customerOutput.Add(Customer.iName + "^" + Customer.iSurname + "^" + Customer.iID + "^" + Customer.iEmail + "^" + Customer.iHomeAddress + "^" + Customer.iMobile + "^" + Customer.iUsername + "^" + Customer.iPassword +"^"+Customer.iCoffeePoints);
       }
   File.WriteAllLines("customer.txt", customerOutput); 
 }
...