gpt4 book ai didi

C#数字键决定三个数组操作中的哪一个

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:12 26 4
gpt4 key购买 nike

我正在 Visual Studio 中用 C# 构建一个控制台应用程序,旨在执行以下三个功能:

  • 假车商一周内售出的汽车总数
  • 显示员工姓名/一周内假汽车经销商为该周员工销售的汽车
  • 将所有销售数据写入文本文件

  • 每周销售的汽车/员工需要每周随机分配,但销量将在 50 到 200 辆之间,有六名员工在册。

    与其他员工相比,本周最佳员工是一周内售出最多汽车的员工。例如。本是本周最佳员工,因为他卖出了 150 辆汽车,而乔丹卖出了 50 辆。
    CODE:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApp2
    {
    class Program
    {
    static void Main(string[] args)
    {
    string[] stringEmployeeArray = new string[6];
    stringEmployeeArray[0] = "Bob";
    stringEmployeeArray[1] = "Steven";
    stringEmployeeArray[2] = "Jordan";
    stringEmployeeArray[3] = "Lee";
    stringEmployeeArray[4] = "Max";
    stringEmployeeArray[5] = "Ben";

    int[] intCarsSoldArray = new int[4];
    intCarsSoldArray[0] = 50;
    intCarsSoldArray[1] = 100;
    intCarsSoldArray[2] = 150;
    intCarsSoldArray[3] = 200;

    Random rnd = new Random();

    Console.WriteLine("Welcome to the Car Dealership Sales Tracker");
    Console.WriteLine("Press 1 to output the name and number of cars sold for the employee with the highest sales (1) ");
    Console.WriteLine("Press 2 to calculate the total number of cars sold by the company (2) ");
    Console.WriteLine("Press 3 to output all dsales data to a text file (3) ");
    Console.WriteLine("-------------------------------------------");
    Console.WriteLine("Enter option number and hit ENTER");
    int val = 5;
    ConsoleKeyInfo input = Console.ReadKey();
    Console.WriteLine();
    switch (val)
    {
    if (input.Key == ConsoleKey.NumPad1)
    case 1:
    string r = rnd.Next(stringEmployeeArray.Count()).ToString();
    int x = rnd.Next(intCarsSoldArray.Count());
    Console.WriteLine("This weeks employee of the week is(string)stringEmployeeArray[r] + (int)intCarsSoldArray[x]");
    break;
    if (input.Key == ConsoleKey.NumPad2)
    case 2:
    int sum = intCarsSoldArray.Sum();
    Console.WriteLine("Total cars sold for this week is(intCarsSoldArray.Sum)");
    break;
    if (input.Key == ConsoleKey.NumPad3)
    case 3:
    break;
    }
    }
    }
    }

    它在一种菜单系统上运行,按下的数字键决定一个选项。目前,您可以看到 1 是他/她的汽车销量为一周的员工,一周内销售的汽车总数为 2 号,文本文件写入为 3 号。

    但是,当我输入选项编号并按 Enter 时,程序会自行关闭。

    我想知道的是
  • 按下以检索本周员工数据时如何编码 1
  • 如何编码数字 2 以计算一周的所有销售额
  • 如何在按下将所有这些数据写入一周的文本文件以存储在计算机上时对数字 3 进行编码,以及如何对将数据实际写入文件进行编码。

  • 我还想知道如何发送错误消息,如果用户输入数字 0 或 4 或更多,他们会收到此 WriteLine 消息:“输入 1 到 3 之间的有效数字”。

    作为 C# 的新手,非常感谢任何帮助。

    谢谢
    NEW CODE FOR RUFUS

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApp3
    {
    public class Employee
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int WeeklySales { get; set; }

    public override string ToString()
    {
    return $"{FirstName} {LastName}";
    }
    }
    public class Program
    {
    private static readonly Random Rnd = new Random();

    private static List<Employee> Employees = new List<Employee>
    {
    new Employee {FirstName = "Bob"},
    new Employee {FirstName = "Steven"},
    new Employee {FirstName = "Jordan"},
    new Employee {FirstName = "Lee"},
    new Employee {FirstName = "Max"},
    new Employee {FirstName = "Ben"}
    };
    static void Main()
    {
    GenerateSalesData();
    MainMenu();
    }
    private static void ClearAndWriteHeading(string heading)
    {
    Console.Clear();
    Console.WriteLine(heading);
    Console.WriteLine(new string('-', heading.Length));
    }
    private static void GenerateSalesData()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Generate Sales Data");

    foreach (var employee in Employees)
    {
    employee.WeeklySales = Rnd.Next(50, 201);
    }

    Console.WriteLine("\nSales data has been generated!!");
    }
    private static void MainMenu()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Main Menu");

    Console.WriteLine("1: Display employee of the week information");
    Console.WriteLine("2: Display total number of cars sold by the company");
    Console.WriteLine("3: Write all sales data to a text file");
    Console.WriteLine("4: Generate new weekly sales info");
    Console.WriteLine("5: Exit program\n");
    Console.Write("Enter option number 1 - 5: ");

    // Get input from user (ensure they only enter 1 - 5)
    int input;
    while (!int.TryParse(Console.ReadKey().KeyChar.ToString(), out input) ||
    input < 1 || input > 5)
    {
    // Erase input and wait for valid response
    Console.SetCursorPosition(0, 8);
    Console.Write("Enter option number 1 - 5: ");
    Console.SetCursorPosition(Console.CursorLeft - 1, 8);
    }

    ProcessMenuItem(input);
    }
    private static void ProcessMenuItem(int itemNumber)
    {
    switch (itemNumber)
    {
    case 1:
    DisplayEmployeeOfTheWeekInfo();
    break;
    case 2:
    DisplayTotalSales();
    break;
    case 3:
    WriteSalesToFile();
    break;
    case 4:
    GenerateSalesData();
    break;
    default:
    Environment.Exit(0);
    break;
    }

    Console.Write("\nPress any key to go back to main menu...");
    Console.ReadKey();
    MainMenu();
    }
    private static void DisplayEmployeeOfTheWeekInfo()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Employee of the Week");

    var employeeOfTheWeek = Employees.OrderByDescending(employee => employee.WeeklySales).First();

    Console.WriteLine($"{employeeOfTheWeek} is the employee of the week!");
    Console.WriteLine($"This person sold {employeeOfTheWeek.WeeklySales} cars this week.");
    }
    private static string GetSalesData()
    {
    var data = new StringBuilder();
    data.AppendLine("Employee".PadRight(25) + "Sales");
    data.AppendLine(new string('-', 30));

    foreach (var employee in Employees)
    {
    data.AppendLine(employee.FirstName.PadRight(25) + employee.WeeklySales);
    }

    data.AppendLine(new string('-', 30));
    data.AppendLine("Total".PadRight(25) +
    Employees.Sum(employee => employee.WeeklySales));

    return data.ToString();
    }
    private static void DisplayTotalSales()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Total Sales");

    Console.WriteLine("\nHere are the total sales for the week:\n");
    Console.WriteLine(GetSalesData());
    }
    private static void WriteSalesToFile(string errorMessage = null)
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Write Sales Data To File");

    if (!string.IsNullOrEmpty(errorMessage)) Console.WriteLine($"\n{errorMessage}\n");
    Console.Write("\nEnter the path to the sales data file:");
    var filePath = Console.ReadLine();
    var salesData = GetSalesData();
    var error = false;

    if (ERROR HERE File.Exists(filePath))
    {
    Console.Write("File exists. (O)verwrite or (A)ppend: ");
    var input = Console.ReadKey().Key;

    while (input != ConsoleKey.A && input != ConsoleKey.O)
    {
    Console.Write("Enter 'O' or 'A': ");
    input = Console.ReadKey().Key;
    }

    if (input == ConsoleKey.A)
    {
    ERROR HERE File.AppendAllText(filePath, salesData);
    }
    else
    {
    ERROR HERE File.WriteAllText(filePath, salesData);
    }
    }
    else
    {
    try
    {
    ERROR HERE File.WriteAllText(filePath, salesData);
    }
    catch
    {
    error = true;
    }
    }

    if (error)
    {
    WriteSalesToFile($"Unable to write to file: {filePath}\nPlease try again.");
    }
    else
    {
    Console.WriteLine($"\nSuccessfully added sales data to file: {filePath}");
    }
    }
    }
    }

    最佳答案

    我认为您可能想退后一步检查整体设计。菜单系统有很多可移动的部分,将需要执行的不同任务分解为单独的功能会很有帮助。

    例如,你可以有一个通用函数来清除控制台并显示一个菜单标题,你可以有一个显示菜单选项的方法,你可以有一个用于每个选项本身的方法。这样,您只需从 Main 调用“MainMenu”方法,然后主菜单方法将获取用户输入并根据用户输入的内容调用适当的方法。

    您还可以使用一种随机化员工数据的方法,以便您可以根据需要模拟新的一周。而且,就此而言,存储员工姓名和他或她每周销售额的简单员工类也可以派上用场。

    这就是我将如何做到的。首先是Employee类,它将名称与每周销售额相关联:

    public class Employee
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int WeeklySales { get; set; }

    public override string ToString()
    {
    return $"{FirstName} {LastName}";
    }
    }

    然后在我们的 Program我们可以有一些私有(private)变量来保存员工和 Random 的实例。类(class):
    public class Program
    {
    private static readonly Random Rnd = new Random();

    private static List<Employee> Employees = new List<Employee>
    {
    new Employee {FirstName = "Bob"},
    new Employee {FirstName = "Steven"},
    new Employee {FirstName = "Jordan"},
    new Employee {FirstName = "Lee"},
    new Employee {FirstName = "Max"},
    new Employee {FirstName = "Ben"}
    };

    然后在我们的 Main方法我们可以只调用一个方法来获取一些随机销售数据,并调用另一个方法来显示主菜单:
        private static void Main()
    {
    GenerateSalesData();
    MainMenu();
    }

    在进入这些方法之前,让我们创建一个简单的方法来清除控制台并写入标题行,然后是虚线(用作下划线):
        private static void ClearAndWriteHeading(string heading)
    {
    Console.Clear();
    Console.WriteLine(heading);
    Console.WriteLine(new string('-', heading.Length));
    }

    现在为我们的员工生成随机数据的方法。我们所要做的就是遍历我们的 employees并且,对于每一个,选择一个介于 50 到 200 之间的随机数并将其分配给 Employee.WeeklySales属性(property):
        private static void GenerateSalesData()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Generate Sales Data");

    foreach (var employee in Employees)
    {
    employee.WeeklySales = Rnd.Next(50, 201);
    }

    Console.WriteLine("\nSales data has been generated!!");
    }

    还有一个显示主菜单。请注意,我们对用户输入进行了一些验证,以确保它可以转换为 int(使用 int.TryParse 方法)并且 int 在我们指定的范围内。当我们得到有效输入时,我们调用不同的方法来处理该输入:
        private static void MainMenu()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Main Menu");

    Console.WriteLine("1: Display employee of the week information");
    Console.WriteLine("2: Display total number of cars sold by the company");
    Console.WriteLine("3: Write all sales data to a text file");
    Console.WriteLine("4: Generate new weekly sales info");
    Console.WriteLine("5: Exit program\n");
    Console.Write("Enter option number 1 - 5: ");

    // Get input from user (ensure they only enter 1 - 5)
    int input;
    while (!int.TryParse(Console.ReadKey().KeyChar.ToString(), out input) ||
    input < 1 || input > 5)
    {
    // Erase input and wait for valid response
    Console.SetCursorPosition(0, 8);
    Console.Write("Enter option number 1 - 5: ");
    Console.SetCursorPosition(Console.CursorLeft - 1, 8);
    }

    ProcessMenuItem(input);
    }

    这是处理输入的方法,它使用 switch输入值上的语句,然后为该命令调用适当的方法:
        private static void ProcessMenuItem(int itemNumber)
    {
    switch (itemNumber)
    {
    case 1:
    DisplayEmployeeOfTheWeekInfo();
    break;
    case 2:
    DisplayTotalSales();
    break;
    case 3:
    WriteSalesToFile();
    break;
    case 4:
    GenerateSalesData();
    break;
    default:
    Environment.Exit(0);
    break;
    }

    Console.Write("\nPress any key to go back to main menu...");
    Console.ReadKey();
    MainMenu();
    }

    要显示本周的员工,我们所要做的就是订购我们的 employeesWeeklySales 列出属性,并选择第一个:
        private static void DisplayEmployeeOfTheWeekInfo()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Employee of the Week");

    var employeeOfTheWeek = Employees
    .OrderByDescending(employee => employee.WeeklySales)
    .First();

    Console.WriteLine($"{employeeOfTheWeek} is the employee of the week!");
    Console.WriteLine(
    $"This person sold {employeeOfTheWeek.WeeklySales} cars this week.");
    }

    现在,在我们开始显示总销售额之前,我注意到我们确实有两个销售信息选项。一个将信息写入控制台窗口,另一个将其写入文件。我们不应该使用几乎完全相同的代码创建两个方法,而应该只创建一个返回数据的方法,然后其他方法可以调用它并将该数据写入控制台或文件。
    GetSalesData方法循环遍历我们所有的员工并显示他们的销售额,以及最后的总销售额:
        private static string GetSalesData()
    {
    var data = new StringBuilder();
    data.AppendLine("Employee".PadRight(25) + "Sales");
    data.AppendLine(new string('-', 30));

    foreach (var employee in Employees)
    {
    data.AppendLine(employee.FirstName.PadRight(25) + employee.WeeklySales);
    }

    data.AppendLine(new string('-', 30));
    data.AppendLine("Total".PadRight(25) +
    Employees.Sum(employee => employee.WeeklySales));

    return data.ToString();
    }

    现在我们可以调用此方法将其显示到控制台:
        private static void DisplayTotalSales()
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Total Sales");

    Console.WriteLine("\nHere are the total sales for the week:\n");
    Console.WriteLine(GetSalesData());
    }

    我们可以使用另一种方法将其写入文件(我们也从该方法中调用 GetSalesData)。

    请注意,我们在此方法中有一些额外的东西来从用户那里获取文件路径,检查文件是否存在,然后询问他们是否要覆盖文件或附加到文件。我还输入了 try/catch阻止重试该方法(通过从自身调用它,并带有错误消息)以防出现某些文件 I/O 错误:
        private static void WriteSalesToFile(string errorMessage = null)
    {
    ClearAndWriteHeading("Car Dealership Sales Tracker - Write Sales Data To File");

    if (!string.IsNullOrEmpty(errorMessage)) Console.WriteLine($"\n{errorMessage}\n");
    Console.Write("\nEnter the path to the sales data file: ");
    var filePath = Console.ReadLine();
    var salesData = GetSalesData();
    var error = false;

    if (File.Exists(filePath))
    {
    Console.Write("File exists. (O)verwrite or (A)ppend: ");
    var input = Console.ReadKey().Key;

    while (input != ConsoleKey.A && input != ConsoleKey.O)
    {
    Console.Write("Enter 'O' or 'A': ");
    input = Console.ReadKey().Key;
    }

    if (input == ConsoleKey.A)
    {
    File.AppendAllText(filePath, salesData);
    }
    else
    {
    File.WriteAllText(filePath, salesData);
    }
    }
    else
    {
    try
    {
    File.WriteAllText(filePath, salesData);
    }
    catch
    {
    error = true;
    }
    }

    if (error)
    {
    WriteSalesToFile($"Unable to write to file: {filePath}\nPlease try again.");
    }
    else
    {
    Console.WriteLine($"\nSuccessfully added sales data to file: {filePath}");
    }
    }

    无论如何,我知道它有很多代码,但希望它能给您一些想法,让您了解如何将程序的各个部分分解为方法,使其更具可读性、可维护性和更易于使用。

    输出

    以下是不同菜单的一些屏幕截图:

    enter image description here

    关于C#数字键决定三个数组操作中的哪一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49652605/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com