Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#数字键决定三个数组操作中的哪一个_C#_Arrays_Menu - Fatal编程技术网

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

C#数字键决定三个数组操作中的哪一个,c#,arrays,menu,C#,Arrays,Menu,我正在Visual Studio中用C#构建一个控制台应用程序,旨在实现以下三个功能: 假冒汽车经销商一周内售出的汽车总数 显示员工姓名/假冒汽车经销商为本周最佳员工在一周内售出的汽车 将所有销售数据写入文本文件 本周售出的汽车/员工需要每周进行随机抽样,但销量将在50至200辆之间,有6名员工在册 与其他员工相比,本周最佳员工是一周内售出汽车最多的员工。本是本周最佳员工,他卖出150辆汽车,而乔丹卖出50辆 CODE: using System; using System.Collectio

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

  • 假冒汽车经销商一周内售出的汽车总数
  • 显示员工姓名/假冒汽车经销商为本周最佳员工在一周内售出的汽车
  • 将所有销售数据写入文本文件
  • 本周售出的汽车/员工需要每周进行随机抽样,但销量将在50至200辆之间,有6名员工在册

    与其他员工相比,本周最佳员工是一周内售出汽车最多的员工。本是本周最佳员工,他卖出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

    然而,当我输入一个选项号并点击回车时,程序会自动关闭

    我想知道的是

  • 按此键检索每周员工数据时如何对编号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}");
                }
            }
        }
    }
    
    鲁弗斯的新代码
    使用制度;
    使用System.Collections.Generic;
    使用System.Linq;
    使用系统文本;
    使用System.Threading.Tasks;
    名称空间控制台AP3
    {
    公营雇员
    {
    公共字符串名{get;set;}
    公共字符串LastName{get;set;}
    public int WeeklySales{get;set;}
    公共重写字符串ToString()
    {
    返回$“{FirstName}{LastName}”;
    }
    }
    公共课程
    {
    私有静态只读随机Rnd=new Random();
    私有静态列表员工=新列表
    {
    新员工{FirstName=“Bob”},
    新员工{FirstName=“Steven”},
    新员工{FirstName=“Jordan”},
    新员工{FirstName=“Lee”},
    新员工{FirstName=“Max”},
    新员工{FirstName=“Ben”}
    };
    静态void Main()
    {
    GenerateSalesData();
    主菜单();
    }
    私有静态无效ClearAndWriteHeading(字符串标题)
    {
    Console.Clear();
    控制台写入线(标题);
    WriteLine(新字符串('-',heading.Length));
    }
    私有静态void GenerateSalesData()
    {
    ClearAndWriteHeading(“汽车经销商销售跟踪器-生成销售数据”);
    foreach(员工中的var员工)
    {
    employee.WeeklySales=Rnd.Next(50201);
    }
    Console.WriteLine(“\n已生成销售数据!!”);
    }
    私有静态void主菜单()
    {
    清除并写入标题(“汽车经销商销售跟踪-主菜单”);
    Console.WriteLine(“1:显示本周员工信息”);
    Console.WriteLine(“2:显示公司销售的汽车总数”);
    Console.WriteLine(“3:将所有销售数据写入文本文件”);
    Console.WriteLine(“4:生成新的每周销售信息”);
    Console.WriteLine(“5:退出程序\n”);
    控制台。写入(“输入选项号1-5:”);
    //从用户处获取输入(确保他们只输入1-5)
    int输入;
    而(!int.TryParse(Console.ReadKey().KeyChar.ToString(),out-input)||
    输入<1 | |输入>5)
    {
    //擦除输入并等待有效响应
    控制台。设置光标位置(0,8);
    控制台。写入(“输入选项号1-5:”);
    Console.SetCursorPosition(Console.CursorLeft-1,8);
    }
    ProcessMenuItem(输入);
    }
    私有静态void ProcessMenuItem(int itemNumber)
    {
    开关(项目编号)
    {
    案例1:
    DisplayEmployeeOfWeekinfo();
    打破
    案例2:
    DisplayTotalSales();
    打破
    案例3:
    WriteSalesToFile();
    打破
    案例4:
    GenerateSalesData();
    打破
    违约:
    环境。退出(0);
    打破
    }
    控制台。写入(“\n按任意键返回主菜单…”);
    Console.ReadKey();
    主菜单();
    }
    私有静态void显示EmployeeOfWeekinfo()
    {
    清晰和书面标题(“汽车经销商销售跟踪-本周最佳员工”);
    var employeeofweek=Employees.OrderByDescending(employee=>employee.WeeklySales.First();
    Console.WriteLine($“{employeeofweek}是本周最佳员工!”);
    Console.WriteLine($“此人本周出售了{employeeofweek.WeeklySales}辆汽车。”);
    }
    私有静态字符串GetSalesData()
    {
    var data=新的StringBuilder();
    数据.AppendLine(“Employee”.PadRight(25)+“Sales”);
    data.AppendLine(新字符串('-',30));
    foreach(员工中的var员工)
    {
    data.AppendLine(employee.FirstName.PadRight(25)+employee.WeeklySales);
    }
    data.AppendLine(新字符串('-',30));
    数据.AppendLine(“总计”).PadRight(25)+
    雇员.总数
    
    switch (input.Key)
    {
        case ConsoleKey.NumPad1:
            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;
        case ConsoleKey.NumPad2:
            int sum = intCarsSoldArray.Sum();
            Console.WriteLine("Total cars sold for this week is(intCarsSoldArray.Sum)");
            break;
        case ConsoleKey.NumPad2:
            break;
    }
    
    switch (input.Key)
    {
        ... //other cases
        case default:
            Console.WriteLine("You pressed a wrong key");
            break;
    }
    
    using(FileStream fs = new FileStream("OutputFile.txt"))
    using(StreamWriter writer = new StreamWriter(fs))
    {
        writer.WriteLine("This is the first line of the text file");
        writer.Write("No new line here");
    }
    
    Console.WriteLine("This weeks employee of the week is(string)stringEmployeeArray[r] + (int)intCarsSoldArray[x]");
    
    Console.WriteLine("This weeks employee of the week is " + stringEmployeeArray[r] + " " + intCarsSoldArray[x]);
    
    Console.WriteLine("Total cars sold for this week is(intCarsSoldArray.Sum)");
    
    Console.WriteLine("Total cars sold for this week is" + sum);
    
    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"}
        };
    
        private 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 (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}");
            }
        }