I am building a console app in C# within Visual Studio which is intended to do these three functions:
- Total the number of cars sold in a week by a fake car dealer
- Display employee name/cars sold in one week by a fake car dealer for an employee of the week
- Write all the sales data to a text file
The cars sold/employee of the week needs to be randomised on a week by week basis but sales will be between 50 and 200, with six staff on the books.
The employee of the week is the one who has sold the most cars in a week versus the other staff. E.g. Ben is employee of the week as he sells 150 cars versus Jordan at 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;
}
}
}
}
It runs on a sort of menu system where the number key pressed decides on a option. At the moment, you can see 1 is to do employee of the week with his/her cars sold, total cars sold in a week is number 2 and text file writing is number 3.
However, when I enter a option number and hit enter the program shuts itself down.
What I would like to know is
- How to code number 1 when pressed to retrieve employee of the week data
- How to code number 2 pressed to calculate all sales for a week
- How to code number 3 when pressed to write all this data for a week to a text file to be stored on the computer and how to code the actual writing of the data to the file.
I would also like to know how to do an error message whereby if the user enters a number of 0 or 4 or more they get this WriteLine message: "Enter a valid number between 1 and 3".
Being new to C#, any help greatly appreciated.
Thanks
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}");
}
}
}
}