C # Вход в систему / регистрация простого консольного приложения

#c# #console-application

#c# #консольное приложение

Вопрос:

Когда я создаю пользователя, он сохраняется в строке, но когда я пытаюсь войти с тем же именем (почему-то оно не существует в строке …)

 using System;

namespace Exercise4
{
class Program
{
    static void Main(string[] args)
    {
        Start:
        Console.WriteLine("Za login stisnete 1 ili za register 2");
        var input = Console.ReadLine();



        bool successfull = false;
        while (!successfull)
        {
            var arrUsers = new Users[]
        {
            new Users("tomas","samsung",2605),
            new Users("stefan","pasle",15),
            new Users("dimitar","jovanov",32)
        };  
            if (input == "1")
            {
                Console.WriteLine("Write your username:");
                var username = Console.ReadLine();
                Console.WriteLine("Enter your password:");
                var password = Console.ReadLine();


                foreach (Users user in arrUsers)
                {
                    if (username == user.username amp;amp; password == user.password)
                    {
                        Console.WriteLine("You have successfully logged in !!!");
                        Console.ReadLine();
                        successfull = true;
                        break;
                    }
                    else if (username != user.username || password != user.password)
                    {
                        Console.WriteLine("Your username or password is incorect, try again !!!");
                        Console.ReadLine();

                        break;

                    }
                }

            }

            else if (input == "2")
            {

                Console.WriteLine("Enter your username:");
                var username = Console.ReadLine();

                Console.WriteLine("Enter your password:");
                var password = Console.ReadLine();

                Console.WriteLine("Enter your id:");
                int id = int.Parse(Console.ReadLine());


                Array.Resize(ref arrUsers, arrUsers.Length   1);
                arrUsers[arrUsers.Length - 1] = new Users(username,password, id);
                successfull = true;
                goto Start;



            }
            else
            {
                Console.WriteLine("Try again !!!");
                break;


            }

        }

    }

}

}
  

Не могу понять, как это сделать.

Комментарии:

1. Спросите себя: «После регистрации все возвращается к начальной метке. Что происходит с arrUsers , когда оно снова входит в цикл?»

2. удаляет их? : D но как поместить start в цикл while …. или что-нибудь подобное этому? 😀 bool successfull = false; в то время как (!успешно) { Запуск: Консоль. Строка записи («Для входа в систему необходимо ввести 1 или для входа в регистр 2»); переменный ввод = Консоль. ReadLine (); var arrUsers = новые пользователи [] я сделал это, но по-прежнему без желаемого эффекта -_- кстати, там написано: Для входа нажмите 1 для регистрации 2

3. я не могу понять, в чем моя ошибка -_- я знаю, что это начинается снова, но …… я выполнял отладку с ним, но не могу просто понять, что он сохраняет их, и когда он запускается, удаляет их … не знаю почему

4. Попробуйте избавиться от метки Start и goto инструкции. Посмотрите, что получится. Помимо этого, используйте отладчик для проверки состояния вашей программы, чтобы вы могли получить лучшее представление о том, что происходит и что вам нужно изменить.

Ответ №1:

 class Program
{
    static void Main(string[] args)
    {
        var arrUsers = new Users[]
        {
            new Users("tomas","samsung",2605),
            new Users("stefan","pasle",15),
            new Users("dimitar","jovanov",32)
        };

        Start:
        Console.WriteLine("Za login stisnete 1 ili za register 2");
        var input = Console.ReadLine();



        bool successfull = false;
        while (!successfull)
        {

            if (input == "1")
            {
                Console.WriteLine("Write your username:");
                var username = Console.ReadLine();
                Console.WriteLine("Enter your password:");
                var password = Console.ReadLine();


                foreach (Users user in arrUsers)
                {
                    if (username == user.username amp;amp; password == user.password)
                    {
                        Console.WriteLine("You have successfully logged in !!!");
                        Console.ReadLine();
                        successfull = true;
                        break;
                    }
                }

                if (!successfull)
                {
                    Console.WriteLine("Your username or password is incorect, try again !!!");
                }

            }

            else if (input == "2")
            {

                Console.WriteLine("Enter your username:");
                var username = Console.ReadLine();

                Console.WriteLine("Enter your password:");
                var password = Console.ReadLine();

                Console.WriteLine("Enter your id:");
                int id = int.Parse(Console.ReadLine());


                Array.Resize(ref arrUsers, arrUsers.Length   1);
                arrUsers[arrUsers.Length - 1] = new Users(username, password, id);
                successfull = true;
                goto Start;

            }
            else
            {
                Console.WriteLine("Try again !!!");
                break;


            }

        }

    }
}

public class Users
{
    public string username;
    public string password;
    private int id;

    public Users(string username, string password, int id)
    {
        this.username = username;
        this.password = password;
        this.id = id;
    }
}
  

Я внес некоторые изменения в ваш код, пожалуйста, проверьте разницу

Я разместил arrUsers перед запуском, чтобы ссылка не менялась при запуске