从用户输入和打印列表中添加项目到控制台

发布于 2025-02-13 03:44:59 字数 7272 浏览 1 评论 0原文

我正在制作一个简单的控制台编程。该程序应该为用户提供一个控制台,该控制台将为您提供三个选择:将员工添加到列表中,将员工从列表中删除,然后退出。我正在尝试创建一个列表,该列表将在用户输入初始化后将其添加到列表中。之后,我想打印列表以进行控制,但是列表不会保留任何输入。如果有人知道怎么了,请告诉我!另外,我是编码的新手,因此对广泛的解释非常感谢。谢谢你!

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;
                }
            }
        }
    }
}

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(
quot;Could not find {employeeToBeDeleted}");
                        break;


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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一身仙ぐ女味 2025-02-20 03:45:00

有一个通过nuget安装的库, spectre.console.console.console ,如果您了解如何与简单的类一起工作,这会使生活更轻松。

Spectre.Console软件包已安装后,您需要使用语句使用Spectre.Console; for All类使用以下。关于课程,我只为员工模型做了三个属性,如果对此解决方案感兴趣,则需要添加其余属性。如果您被卡住了,请参见

从代表菜单项的模型/类开始

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

}

介绍菜单

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;
    }
}

创建一个类,用于在program.cs中 主代码。遵循这种模式,有一条清晰的途径来处理各种操作和退出。

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;
            }
        }
    }
}

要了解如何处理添加新项目并在列表中列出项目以下代码显示如何。

  • 首先和姓氏不能为空的,提示在那里留在那里。您可以添加一条验证消息(请参阅文档)
  • 薪水必须是双重的,

因此您有一些简单的验证。

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();
    }
}

某些屏幕截图

There is a library installed via NuGet, Spectre.Console which makes life easier if you understand how to work with simple classes.

Once the Spectre.Console package has been installed you need the following using statement 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. 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

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. 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

enter image description here

孤寂小茶 2025-02-20 03:45:00

您以这种方式进行循环设置:

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

因此,每次循环时,都会删除员工列表并获得新的列表。尝试交换订单:

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

这样,您可以使用新的员工列表启动程序,并在程序运行时使用相同的列表。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文