I would love to have some suggestion for my program, I would prefer no more suggestion to use Linq and other advanced concepts as I would like to keep it as simple as possible for now. I love suggestion on the structure of the program and methods and so on. If needed to condense the program into the basics, only the things in the menu are needed. Maybe I should use an constructor in the BeverageData class instead of property?
The Menu class is in the bottom of the code block. I've tried to split it up for readability. The code is working and without bugs as far as I know.
public enum BeverageType
{
Soda,
Juice,
Water,
Alcohol
}
public class BeverageData // Skapar
{
public string Name { set; get; }
public BeverageType Type { set; get; }
public decimal Price { set; get; }
public int Size { get; set; }
public override string ToString()
{
return $"{Name} ({Type}) {Size}{"CL"} = {Price:C}";
}
}
The Beverage class, everything related to the list of beverages here.
public class Beverages
{
private static readonly Random Rnd = new Random();
public static BeverageData GetBeverageFromUser()
{
return new BeverageData
{
Name = GetName("Enter name: "),
Price = GetCurrency("Enter cost: "),
Type = GetBeverageType("Enter type: "),
Size = GetSize("Enter size: ")
};
}
public static BeverageData GetRandomBeverage()
{
var names = new List<BeverageData>
{
new BeverageData {Name = "Coke", Price = .75m,
Size = 12, Type = BeverageType.Soda},
new BeverageData {Name = "Pepsi", Price = .75m,
Size = 12, Type = BeverageType.Soda},
new BeverageData {Name = "Sprite", Price = .75m,
Size = 12, Type = BeverageType.Soda},
new BeverageData {Name = "Rootbeer", Price = .75m,
Size = 12, Type = BeverageType.Soda},
new BeverageData {Name = "Orange Juice", Price = .5m,
Size = 10, Type = BeverageType.Juice},
new BeverageData {Name = "Apple Juice", Price = .5m,
Size = 10, Type = BeverageType.Juice},
new BeverageData {Name = "Grape Juice", Price = .5m,
Size = 10, Type = BeverageType.Juice},
new BeverageData {Name = "Water", Price = .25m,
Size = 20, Type = BeverageType.Water},
new BeverageData {Name = "Beer", Price = 2.75m,
Size = 16, Type = BeverageType.Alcohol},
new BeverageData {Name = "Wine", Price = 3.5m,
Size = 9, Type = BeverageType.Alcohol},
};
return names[Rnd.Next(names.Count)];
}
private static BeverageType GetBeverageType(string message)
{
BeverageType beverageType;
Console.Write(message);
while (!Enum.TryParse(Console.ReadLine(), true, out beverageType))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid beverage type");
Console.ResetColor();
Console.Write("Valid beverage types are: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(string.Join(", ", Enum.GetNames(typeof(BeverageType))));
Console.ResetColor();
Console.Write(message);
}
return beverageType;
}
private static string GetName(string message)
{
Console.Write(message);
return Console.ReadLine();
}
private static decimal GetCurrency(string message)
{
decimal result;
Console.Write(message);
while (!decimal.TryParse(Console.ReadLine(), NumberStyles.Currency,
CultureInfo.CurrentCulture, out result))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid number");
Console.ResetColor();
Console.Write(message);
}
return result;
}
private static int GetSize(string message)
{
int result;
Console.Write(message);
while (!int.TryParse(Console.ReadLine(), NumberStyles.Currency, CultureInfo.CurrentCulture, out result))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid Size");
Console.ResetColor();
Console.Write(message);
}
return result;
}
}
Here is my Beverage Crate Class, where there crate is represented and sort of the base class of the program.
class Crate : IEnumerable<BeverageData>
{
private BeverageData[] crate = new BeverageData[24];
private int numberOfBottles = 0;
private const int MaxItems = 24;
public void Add(BeverageData beverage)
{
if (numberOfBottles >= MaxItems)
{
Console.WriteLine("The crate is full. Please remove an item first!");
}
else
{
crate[numberOfBottles] = beverage;
numberOfBottles++;
}
}
public IEnumerator<BeverageData> GetEnumerator()
{
return crate.AsEnumerable().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Remove(string name)
{
try
{
Remove(crate.FirstOrDefault(i =>
i.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
}
catch (Exception)
{
Console.WriteLine("Please only enter name");
}
}
public void Remove(BeverageData beverage)
{
int index = Array.IndexOf(crate, beverage, 0, numberOfBottles);
if (index < 0)
return;
this.RemoveAt(index);
}
/// <summary>
/// Removes the element at the specified index of the Beverage array.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
public void RemoveAt(int index)
{
if (index < numberOfBottles)
{
numberOfBottles--;
Array.Copy(crate, index + 1, crate, index, numberOfBottles - index);
crate[numberOfBottles] = default(BeverageData);
}
}
public void PrintCrate()
{
if (numberOfBottles == 0)
{
Console.WriteLine("There are no items in the crate.");
}
else
{
foreach (var beverage in this)
Console.WriteLine(beverage);
}
}
public void FindBeverageInCrate()
{
string crateBeverageName = Console.ReadLine();
for (int i = 0; i < crate.Length; i++)
{
var bottle = crate[i];
if (bottle == null)
{
continue;
}
if (crate[i].Name == crateBeverageName)
{
Console.WriteLine("Found your beverage {0}", crateBeverageName);
}
}
}
public void SortCrate()
{
int max = crate.Length;
//Yttre loop för att få med hela
for (int i = 1; i < max; i++)
{
//Inre loop för att gå rad per rad
int nrLeft = max - i;
for (int j = 0; j < (max - i); j++)
{
var bottle1 = crate[j];
var bottle2 = crate[j + 1];
if ((bottle1 == null) || (bottle2 == null)) // Kontrollerar att ingen av dem är tom innan den byter plats
{
continue;
}
if (bottle1.Name.CompareTo(bottle2.Name) == 1) // Byter plats
{
var temp = crate[j];
crate[j] = crate[j + 1];
crate[j + 1] = temp;
}
}
}
}
public decimal CalculateTotalInCrate()
{
decimal summa = 0;
foreach (var bottles in crate)
{
if (crate != null && bottles != null)
summa += bottles.Price;
}
Console.WriteLine("The total value of the crate is: ", summa);
return summa;
}
public static int GetInt(string message)
{
int result;
Console.Write(message);
while (!int.TryParse(Console.ReadLine(), out result))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid number");
Console.ResetColor();
Console.Write(message);
}
return result;
}
}
And finally the menu class, the starting point of the program.*
class Menu : Crate
{
static void Main(string[] args)
{
ShowMenu();
Console.WriteLine("\nDone!\nPress any key to exit..."); // Väntar efter input en sista gång efter användaren har tryckt 0
Console.ReadKey();
}
public static void ShowMenu()
{
bool exit = false;
var beverages = new Crate(); // Skapar en instans av klassen Crate som beverage
do
{
Console.WriteLine("[1] Add custom beverage to array");
Console.WriteLine("[2] Remove Bottle from Bottle Crate");
Console.WriteLine("[3] Show Bottle Crate");
Console.WriteLine("[4] Autofill crate");
Console.WriteLine("[5] Sort Bottles in Bottle Crate according to name");
Console.WriteLine("[6] Calculate the Total Cost in Crate");
Console.WriteLine("[7] Search in crate after beverage");
Console.WriteLine("[9] Empty the crate");
Console.WriteLine("[0] Exit the program");
ConsoleKeyInfo info = Console.ReadKey();
int selection;
int.TryParse(info.KeyChar.ToString(), out selection);
switch (selection) // Använder switch för att kunna se vad
{
case 1:
var numBevs = Math.Max(GetInt("How many beverages would you like to enter: "), 0);
for (int i = 0; i < numBevs; i++)
{
Console.WriteLine($"\nEnter beverage #{i + 1} info");
Console.WriteLine("-----------------------");
beverages.Add(Beverages.GetBeverageFromUser()); // Calls the Add function before the GetBeverageFromUser method
Console.WriteLine("-----------------------\n");
}
Console.Clear();
break;
case 2:
Console.Clear();
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine("Please enter the name of the beverage you would like removed: ");
beverages.Remove(Console.ReadLine());
Console.WriteLine("Your beverage has been removed");
break;
case 3:
Console.Clear();
Console.WriteLine("\nHere are the contents of the crate:\n");
Console.ForegroundColor = ConsoleColor.Green;
beverages.PrintCrate();
Console.ResetColor();
break;
case 5:
numBevs = Math.Max(GetInt("How many would you like to be auto-added: "), 0);
for (int i = 0; i < numBevs; i++)
{
beverages.Add(Beverages.GetRandomBeverage());
}
Console.WriteLine("-----------------------\n");
Console.Clear();
break;
case 6:
Console.Clear();
beverages.SortCrate();
Console.WriteLine("The Crate has been sorted");
break;
case 7:
Console.ForegroundColor = ConsoleColor.Red;
beverages.CalculateTotalInCrate();
Console.ResetColor();
break;
case 8:
beverages.FindBeverageInCrate();
Console.WriteLine("This is your beverage?");
break;
case 9:
ShowMenu();
Console.Clear();
Console.WriteLine("Your crate has been emptied");
break;
case 0:
exit = true;
break;
default:
Console.Clear();
Console.WriteLine("An error has occured, try again");
break;
}
} while (!exit);
}
}
crate.FirstOrDefault
and you even implement theIEnumerable<T>
... no advanced stuff, huh? ;-) \$\endgroup\$AsEnumerable
incrate.AsEnumerable().GetEnumerator()
?crate
is an array which is already implementsIEnumerable
. \$\endgroup\$GetEnumerator
on every type that implementsIEnumerable
. \$\endgroup\$