简体   繁体   English

将用户输入的项目添加到列表并将列表打印到控制台

[英]Adding items to list from user input and printing list out to console

I'm making a simple console-program.我正在制作一个简单的控制台程序。 This program is supposed to give the user a console-menu that will give you three choices: To add an employee to a list, remove an employee from the list, and then to exit.这个程序应该给用户一个控制台菜单,它会给你三个选择:将员工添加到列表中,从列表中删除员工,然后退出。 I am trying to create a list that will add different users to the list after they have been initialized by user input.我正在尝试创建一个列表,该列表将在用户输入初始化后将不同的用户添加到列表中。 After that I want to print the list to console, but the list wont hold on to any input.之后我想将列表打印到控制台,但列表不会保留任何输入。 If anyone has a clue whats wrong, please tell me, Also, I am fairly new to coding.如果有人知道出了什么问题,请告诉我,另外,我对编码还很陌生。 so extensive explanations are greatly appreciated.非常感谢如此广泛的解释。 Thank you!谢谢!

using Employees;

namespace Inheritance
{
    public class Program
    {
        static void Main(string[] args)
        {
            bool keepRunning = true;
            while (keepRunning)
            {
                List<Employee> EmployeesList = new List<Employee>();

                 void AddToList(Employee employee)
                {
                    EmployeesList.Add(employee);
                }

                Console.WriteLine("TIFFANYS & CO - PRIVATE PROGRAM TM\nPress the number of the action you want to pursue, and press [ENTER].\n1) Add an Employee\n2) Delete an Employee\n3) Exit");
                var menuChoice = Int32.Parse(Console.ReadLine());
                switch (menuChoice)
                {
                    case 0:
                        foreach (Employee item in EmployeesList)                    
                        {                                                    
                            Console.WriteLine(item.firstName + " " + item.lastName + " " + item.salary);

                        }
                        break;
                    case 1:
                        Console.WriteLine("a) Add a Manager\nb) Add an Engineer\nc) Add a Researcher");
                        var menuChoice1 = Console.ReadLine();

                        switch (menuChoice1)
                        {
                            case "a":


                                Console.WriteLine("Please type in the first name of the manager and press [ENTER]:");
                                string managerFirstName = Console.ReadLine();
                                Console.WriteLine("Please type in the last name of the manager and press [ENTER]:");
                                string managerLastName = Console.ReadLine();
                                Console.WriteLine("Please type in the salary of the manager and press [ENTER]:");
                                int managerSalary = Int32.Parse(Console.ReadLine());
                                Console.WriteLine("Please type in how many meetings the manager will attend weekly and press [ENTER]:");
                                int managerMeetings = Int32.Parse(Console.ReadLine());
                                Console.WriteLine("Please type in how many vacation-weeks the manager has annually and press [ENTER]:");
                                int managerVacationWeeks = Int32.Parse(Console.ReadLine());

                                Manager manager = new(managerFirstName, managerLastName, managerSalary, managerMeetings, managerVacationWeeks);
                                EmployeesList.Add(manager);
                                foreach (var employee in EmployeesList)

                                {
                                    Console.WriteLine(employee);
                                }

                                break;

                            case "b":


                                Console.WriteLine("Please type in the first name of the engineer and press [ENTER]:");
                                string engineerFirstName = Console.ReadLine();
                                Console.WriteLine("Please type in the last name of the engineer and press [ENTER]:");
                                string engineerLastName = Console.ReadLine();
                                Console.WriteLine("Please type in the salary of the engineer and press [ENTER]:");
                                int engineerSalary = Int32.Parse(Console.ReadLine());
                                //Console.WriteLine("Is the engineer able to use C#? If yes, type [yes] and press [ENTER]. If no, type [no] and press [ENTER]:");
                                //string cSkill = Console.ReadLine();
                                //if (cSkill == "yes")
                                //{
                                //    engineer.cSharpSkill = true;
                                //}
                                //else
                                //{
                                //    engineer.cSharpSkill = false;
                                //}
                                Console.WriteLine("How many years of experience does the engineer have? Type the number of years and press [ENTER]:");
                                int engineerExperience = Int32.Parse(Console.ReadLine());
                                Console.WriteLine("What kind of engineering is the engineers field? Please write their field and press [ENTER]:");
                                string engineerField = Console.ReadLine();

                                Engineer engineer = new(engineerFirstName, engineerLastName, engineerSalary, engineerExperience, engineerField);

                                EmployeesList.Add(engineer);

                                break;

                            case "c":


                                Console.WriteLine("Please type in the first name of the researcher and press [ENTER]:");
                                string researcherFirstName = Console.ReadLine();
                                Console.WriteLine("Please type in the last name of the researcher and press [ENTER]:");
                                string researcherLastName = Console.ReadLine();
                                Console.WriteLine("Please type in the salary of the researcher and press [ENTER]:");
                                int researcherSalary = Int32.Parse(Console.ReadLine());
                                Console.WriteLine("What university did the researcher get their Doctorate? Please type in the name of the university and press [ENTER]:");
                                string researcherUniversity = Console.ReadLine();
                                Console.WriteLine("What was the thesis statement of the researchers doctorate? Please type in the thesis question and press [ENTER]:");
                                string researcherThesis = Console.ReadLine();
                                Researcher researcher = new(researcherFirstName, researcherLastName, researcherSalary, researcherUniversity, researcherThesis);

                                EmployeesList.Add(researcher);
                                break;
                        }

                        break;

                    case 2:

                        Console.WriteLine("What is the last name of the engineer to be deleted?");
                        string toDeleteLastName = Console.ReadLine();
                        Employee employeeToBeDeleted = EmployeesList.Find(e => e.lastName == toDeleteLastName);
                        if (employeeToBeDeleted != null)
                            EmployeesList.Remove(employeeToBeDeleted);
                        else
                            Console.WriteLine($"Could not find {employeeToBeDeleted}");
                        break;


                    case 3:
                        keepRunning = false;
                        break;
                }
            }
        }
    }
}

There is a library installed via NuGet, Spectre.Console which makes life easier if you understand how to work with simple classes.通过 NuGet 安装了一个库, Spectre.Console如果您了解如何使用简单的类,它会让生活更轻松。

Once the Spectre.Console package has been installed you need the following using statement using Spectre.Console;安装 Spectre.Console package 后,您需要使用以下using语句using Spectre.Console; for all classes.对于所有班级。 In regard to classes I only did three properties for the Employee model, you need to add the remaining properties if interest in this solution.关于类,我只为 Employee model 做了三个属性,如果对此解决方案感兴趣,您需要添加剩余的属性。 If you get stuck, see full source but for learning try not to use that code.如果您遇到困难,请查看完整源代码,但为了学习尽量不要使用该代码。

Start off with a model/class which represents menu items从代表菜单项的模型/类开始

public class MenuItem
{
    public int Id { get; set; }
    public string Text { get; set; }
    public override string ToString() => Text;

}

Create a class for presenting the menu创建一个 class 用于呈现菜单

public class MenuOperations
{
    public static SelectionPrompt<MenuItem> MainMenu()
    {
        SelectionPrompt<MenuItem> menu = new()
        {
            HighlightStyle = new Style(
                Color.DodgerBlue1, 
                Color.Black, 
                Decoration.None)
        };

        menu.Title("Select an [B]option[/]");
        menu.AddChoices(new List<MenuItem>()
        {
            new MenuItem() {Id = 0, Text = "List employees"},
            new MenuItem() {Id = 1, Text = "Add manager"},
            new MenuItem() {Id = 2, Text = "Add Engineer"},
            new MenuItem() {Id = 3, Text = "Delete"},
            new MenuItem() {Id = -1, Text = "Exit"},
        });

        return menu;
    }
}

Main code in Program.cs. Program.cs 中的主要代码。 Following this pattern there is a clear cut path to handling various operations and exiting.按照这种模式,有一条清晰的路径可以处理各种操作和退出。

class Program
{
    static void Main(string[] args)
    {
        MenuItem menuItem = new MenuItem();

        List<Employee> EmployeesList = new List<Employee>();

        while (menuItem.Id > -1)
        {

            AnsiConsole.Clear();
            menuItem = AnsiConsole.Prompt(MenuOperations.MainMenu());
            switch (menuItem.Id)
            {
                case 0:
                    Operations.List(EmployeesList);
                    break;
                case 1:
                    Console.WriteLine("Add manager");
                    EmployeesList.Add(Operations.AddEmployee());
                    break;
                case 2:
                    Console.WriteLine("Add Engineer");
                    Console.ReadLine();
                    break;
                case 3:
                    Console.WriteLine("Delete");
                    Console.ReadLine();
                    break;
            }
        }
    }
}

To get an idea how to handle adding a new item and listing items in the list the following code shows how.要了解如何处理添加新项目并在列表中列出项目,以下代码显示了如何操作。

  • First and last name can not be empty else the prompt stays there.名字和姓氏不能为空,否则提示会保留在那里。 You can add a validation message (see the docs)您可以添加验证消息(请参阅文档)
  • Salary must be a double工资必须是双倍

With the above in mind you have some simple validation.考虑到以上内容,您可以进行一些简单的验证。

public class Operations
{

    public static Employee AddEmployee()
    {
        Employee employee = new Employee
        {
            FirstName = GetFirstName(),
            LastName = GetLastName(),
            Salary = GetSalary()
        };

        return employee;
    }

    public static string GetFirstName() =>
        AnsiConsole.Prompt(
            new TextPrompt<string>("[white]First name[/]?")
                .PromptStyle("yellow")
                .ValidationErrorMessage("[red]Please enter your first name[/]"));

    public static string GetLastName() =>
        AnsiConsole.Prompt(
            new TextPrompt<string>("[white]Last name[/]?")
                .PromptStyle("yellow")
                .ValidationErrorMessage("[red]Please enter your last name[/]"));

    public static double GetSalary() =>
        AnsiConsole.Prompt(
            new TextPrompt<double>("[white]Salary[/]?")
                .PromptStyle("yellow")
                .ValidationErrorMessage("[red]Please enter salary (numbers only)[/]"));

    public static void List(List<Employee> list)
    {
        if (list.Count == 0)
        {
            AnsiConsole.MarkupLine("Nothing is list, press [b]ENTER[/] to return to menu");
            Console.ReadLine();
            return;
        }

        var table = new Table()
            .RoundedBorder()
            .AddColumn("[b]First[/]")
            .AddColumn("[b]Last[/]")
            .AddColumn("[b]Salary[/]")
            .Alignment(Justify.Center)
            .BorderColor(Color.LightSlateGrey)
            .Title("[yellow]Employee list[/]");

        foreach (var employee in list)
        {
            table.AddRow(employee.FirstName, employee.LastName, employee.Salary.ToString("C"));
        }

        AnsiConsole.Write(table);
        AnsiConsole.MarkupLine("Press [b]ENTER[/] to return to menu");
        Console.ReadLine();
    }
}

Some screenshots一些截图

在此处输入图像描述

You have the loop setup this way:您以这种方式设置了循环:

while (keepRunning)
{
    List<Employee> EmployeesList = new List<Employee>();

So every time you loop you delete the list of employees and get a new one.所以每次你循环你删除员工列表并获得一个新的。 Try swapping the order:尝试交换顺序:

List<Employee> EmployeesList = new List<Employee>();
while (keepRunning)
{

This way you start your program with a fresh employee list and use that same list while your program is running.通过这种方式,您可以使用新的员工列表启动程序,并在程序运行时使用相同的列表。

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

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