简体   繁体   English

将用户输入添加到现有列表中

[英]Adding user Input into an existing List

I'm creating a .NET core app where the user can add, edit, delete or view players and some stats.我正在创建一个 .NET 核心应用程序,用户可以在其中添加、编辑、删除或查看播放器和一些统计信息。 I've got an abstract Players Class with children(HockeyPlayers, BasketBall players etc)我有一个抽象的 Players Class 和孩子(曲棍球运动员,篮球运动员等)

In my Main class I have created a List and populated it with some default players.在我的主要 class 中,我创建了一个列表并用一些默认播放器填充它。

List<Player> players = new List<Player>()
          {
              new HockeyPlayer
              {
                  PlayerId = 1,
                  PlayerName = "Mitch marner",
                  TeamName = "Toronto Maple Leafs",
                  GamesPlayed = 5,
                  Assists = 12,
                  Goals = 7
              },
              new HockeyPlayer
              {
                  PlayerId = 2,
                  PlayerName = "Nazem kadri",
                  TeamName = "Colorado Avalanche",
                  GamesPlayed = 12,
                  Assists = 11,
                  Goals = 8
              },
              new BasketballPlayer
              {
                  PlayerId = 3,
                  PlayerName = "Stephen Curry",
                  TeamName = "Golden State Warriors",
                  GamesPlayed = 4,
                  FieldGoals = 30,
                  ThreePointer = 6
              },
              

Now further down in my main class I have a method used to add a new HockeyPlayer现在在我的主要 class 进一步向下,我有一种方法用于添加新的 HockeyPlayer

static void addHockeyPlayer()
        {
            Console.WriteLine("\nAdding Hockey PLayer");
            Console.WriteLine("\nEnter Player Name:");
            bool valid = false;
            while (!valid)
            {
                string nameInput = Console.ReadLine();
                if (string.IsNullOrEmpty(nameInput) || Regex.IsMatch(nameInput, @"^\d+$"))
                {
                    Console.WriteLine("\nInvalid Input. Please try again");
                    Console.Write("Enter Player Name:");
                    valid = false;
                }
                else
                {
                    //new HockeyPlayer
                    //{
                        //PlayerId = 6,
                        //PlayerName = nameInput
                    //};
                    break;
                }
            }
            Console.WriteLine("Enter Player Team:");
            while (!valid)
            {
                string teamInput = Console.ReadLine();
                if (string.IsNullOrEmpty(teamInput) || Regex.IsMatch(teamInput, @"^\d+$"))
                {
                    Console.WriteLine("\nInvalid Input. Please try again");
                    Console.Write("Enter Player Name:");
                    valid = false;
                }
                else
                {
                    ////////

                }
            }
        }

As you can see, after every WriteLine(PlayerName,TeamName,GamesPlayed,Goals,Assists) I need to validate the Input.如您所见,在每个 WriteLine(PlayerName,TeamName,GamesPlayed,Goals,Assists) 之后,我都需要验证输入。 I'm not sure how I should be putting all the validated inputs together and then adding it to the List as a complete player?我不确定我应该如何将所有经过验证的输入放在一起,然后将其作为完整的播放器添加到列表中?

UPDATE : so you can return a new HockeyPlayer object.更新:所以你可以返回一个新的HockeyPlayer object。 I would also get rid of PlayerId property since the index in the list can represent this number:我也会去掉PlayerId属性,因为列表中的索引可以代表这个数字:

public HockeyPlayer createHockeyPlayer() 
{
    HockeyPlayer hockeyPlayer = new HockeyPlayer();

    Console.WriteLine("\nAdding Hockey PLayer");

    while(true)
    {
        Console.WriteLine("\nEnter Player Name: ");
        hockeyPlayer.NameInput = Console.ReadLine();

        if(string.IsNullOrEmpty(hockeyPlayer.NameInput) || Regex.IsMatch(hockeyPlayer.NameInput, @"^\d+$"))
        {
            // complain about bad input
        }
        else
        {
            break;
        }
    }

    while(true)
    {
        Console.WriteLine("\nEnter Player Team: ");
        hockeyPlayer.TeamInput = Console.ReadLine();

        if(string.IsNullOrEmpty(hockeyPlayer.TeamInput) || Regex.IsMatch(hockeyPlayer.TeamInput, @"^\d+$"))
        {
            // complain about bad input
        }
        else
        {
            break;
        }
    }

     hockeyPlayer.GamesPlayed = 0;
     hockeyPlayer.Assists = 0;
     hockeyPlayer.Goals = 0;

    return hockeyPlayer;
}

And then you can add the HockeyPlayer outside of this method:然后您可以在此方法之外添加HockeyPlayer

List<Player> players = new List<Player>();
players.Add(HockeyPlayer());

To avoid the repetitive validation code, you could extract it into a method that takes in a string as a prompt for the user and a Func<string, bool> that represents the function to be used to validate the input:为了避免重复的验证代码,您可以将其提取到一个方法中,该方法接受一个string作为用户的提示,以及一个表示 function 的Func<string, bool>用于验证输入:

public static string GetStringFromUser(string prompt, Func<string, bool> validator = null)
{
    var isValid = true;
    string result;

    do
    {
        if (!isValid)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Invalid input, please try again.", ConsoleColor.Red);
            Console.ResetColor();
        }
        else isValid = false;

        Console.Write(prompt);
        result = Console.ReadLine();
    } while (validator != null && !validator.Invoke(result));

    return result;
}

We can do something similar for the int fields, to ensure they enter a number, and it isn't negative:我们可以对int字段做类似的事情,以确保它们输入一个数字,并且它不是负数:

public static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    var isValid = true;
    int result;

    do
    {
        if (!isValid)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Invalid input, please try again.", ConsoleColor.Red);
            Console.ResetColor();
        }
        else isValid = false;

        Console.Write(prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
                (validator != null && !validator.Invoke(result)));

    return result;
}

Then, you can just use the result of these methods to populate the items in a new instance of the Player class:然后,您可以使用这些方法的结果来填充Player class 的新实例中的项目:

static void AddHockeyPlayer(List<Player> players)
{
    Console.WriteLine("\nAdding Hockey PLayer");

    // Create some functions to validate input
    Func<int, bool> numberValidator = x => x >= 0;
    Func<string, bool> nameValidator = x => !string.IsNullOrEmpty(x) && 
        !Regex.IsMatch(x, @"^\d+$");

    // Make sure players isn't null
    if (players == null) players = new List<Player>();

    // Add a new player using our new methods to get the user input
    players.Add(new Player
    {
        PlayerName = GetStringFromUser("Enter player name: ", nameValidator),
        TeamName = GetStringFromUser("Enter team name: ", nameValidator),
        PlayerId = GetIntFromUser("Enter player id: ", numberValidator),
        Assists = GetIntFromUser("Enter number of assists: ", numberValidator),
        GamesPlayed = GetIntFromUser("Enter number of games played: ", numberValidator),
        Goals = GetIntFromUser("Enter number of goals: ", numberValidator)
    });
}

Then in you main method, you would just call it like:然后在你的主要方法中,你可以这样称呼它:

AddHockeyPlayer(players);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM