进入板条箱阵列的对象列表

时间:2017-07-15 19:22:44

标签: c#

我正在尝试实现一个将由饮料列表填充的Beverage Crate数组,但是我在创建数组时遇到了问题。我已尝试在程序中做一些临时解决方案,但由于crate数组不能正常工作,我无法让它们工作。问题出在Crate Class和主类中,其中add-drink方法不起作用。

如何在不使用包列表的情况下让我的数组工作?   我得到的一个错误是

{
            if (crate.Count >= MaxItems)
            {
                Console.WriteLine("The crate is full. Please remove an item first!");
            }
            else
            {
                crate.Add(beverage);

我得到一个编译错误操作数> =不能应用于int类型的方法组,饮料不包含在crate.add行中添加的定义

class Menu : Crate
        {
            static void Main(string[] args)
            {
                ShowMenu(); // Wait for input before closing
                Console.WriteLine("\nDone!\nPress any key to exit...");
                Console.ReadKey();
            }
            public static void ShowMenu()
            {
                bool exit = false;
                var beverages = new Crate();
                do
                {
                    Console.WriteLine("[1] Add Bottle from existing list to Bottle Crate");// TODO IMPLEMENT 
                    Console.WriteLine("[2] Remove Bottle from Bottle Crate");
                    Console.WriteLine("[3] Show Bottle Crate");// TODO IMPLEMENT
                    Console.WriteLine("[4] Add custom beverage to array");
                    Console.WriteLine("[5] Remove Beverage from list"); // TODO
                    Console.WriteLine("[6] Sort Bottles in Bottle Crate according to name");// TODO IMPLEMENT
                    Console.WriteLine("[7] AutoFill crate"); 
                    Console.WriteLine("[8] Calculate the Total Cost in Crate"); // TODO IMPLEMENT
                    Console.WriteLine("[9] Search in crate after beverage");   // TODO IMPLEMENT
                    Console.WriteLine("[0] Exit the program");

                    ConsoleKeyInfo info = Console.ReadKey();
                    int selection;
                    int.TryParse(info.KeyChar.ToString(), out selection);

                    switch (selection)
                    {
                        case 1:

                            break;
                        case 2:
                            //beverages.Remove();
                            //break;
                        case 3:
                            Console.WriteLine("\nHere are the contents of the crate:\n");
                            Console.ForegroundColor = ConsoleColor.Green;
                            beverages.PrintCrate();
                            Console.ResetColor();
                            break;
                        case 4:
                            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());
                                Console.WriteLine("-----------------------\n");
                            }
                            break;
                        //case 5:
                        //    Remove_Beverage();
                        //    break;
                        //case 6:
                        //    SortCrate();
                        //    break;
                        case 7:
                            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");
                            break;
                        //case 8:
                        //    Calc_Total();
                        //    break;
                        //case 9:
                        //    //SearchArray();
                        //    break;
                        case 0:
                            exit = true;
                            break;
                        default:
                            ShowMenu();
                            break;
                    }

                    } while (!exit) ;
                }
            }
        }


    class Crate : IEnumerable<Beverage>
        {
            private Beverage[] crate = new Beverage[24];
            private int numberOfBottles = 0;

            private const int MaxItems = 24;
            public void Add(Beverage beverage)
            {
                if (crate.Count >= MaxItems)
                {
                    Console.WriteLine("The crate is full. Please remove an item first!");
                }
                else
                {
                    crate.Add(beverage);
                }
            }
            public IEnumerator<Beverage> GetEnumerator()
            {
                return crate.AsEnumerable().GetEnumerator();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }

            public void Remove(string name)
            {
                Remove(crate.FirstOrDefault(i =>
                    i.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
            }

            public void Remove(Beverage beverage)
            {
                if (crate.Contains(beverage)) crate.Remove(beverage);
            }

            public void PrintCrate()
            {
                if (crate.Count == 0)
                {
                    Console.WriteLine("There are no items in the crate.");
                }
                else
                {
                    crate.ForEach(Console.WriteLine);
                }
            }
            //public int find_Soda(string drinkname)
            //{
            //    for (int i = 0; i < bottles.Length; i++)
            //    {
            //        if (bottles[i].Drink_name == drinkname) //My feeble attempts
            //            return i;
            //    }
            //    return -1;
            //}
            //public void sort_Sodas_name()
            //{
            //    int max = bottles.Length;
            //    //Outer loop for complete [bottles]
            //    for (int i = 1; i < max; i++)
            //    {
            //        //Inner loop for row by row
            //        int nrLeft = max - i;
            //        for (int j = 0; j < (max - i); j++)
            //        {
            //            var bottle1 = bottles[j];
            //            var bottle2 = bottles[j + 1];

            //            if ((bottle1 == null) || (bottle2 == null))
            //            {
            //                continue;
            //            }
            //            if (bottle1.name.CompareTo(bottle2.Drink_name) == 1)
            //            {
            //                var temp = bottles[j];
            //                bottles[j] = bottles[j + 1];
            //                bottles[j + 1] = temp;

            //public int calc_total()
            //{
            //    int temp = 0;
            //    for (int i = 0; i < bottleCount(); i++)
            //    {
            //        temp = temp + (bottles[i].Price);
            //    }
            //    return temp;

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




     public class Beverages
        {
            private static readonly Random Rnd = new Random();

            public static Beverage GetBeverageFromUser()
            {
                return new Beverage
                {
                    Name = GetName("Enter name: "),
                    Price = GetCurrency("Enter cost: "),
                    Type = GetBeverageType("Enter type: "),
                    Size = GetSize("Enter size: ")
                };
            }

            public static Beverage GetRandomBeverage()
            {
                var names = new List<Beverage>
            {
                new Beverage {Name = "Coke", Price = .75m,
                    Size = 12, Type = BeverageType.Soda},
                new Beverage {Name = "Pepsi", Price = .75m,
                    Size = 12, Type = BeverageType.Soda},
                new Beverage {Name = "Sprite", Price = .75m,
                    Size = 12, Type = BeverageType.Soda},
                new Beverage {Name = "Rootbeer", Price = .75m,
                    Size = 12, Type = BeverageType.Soda},
                new Beverage {Name = "Orange Juice", Price = .5m,
                    Size = 10, Type = BeverageType.Juice},
                new Beverage {Name = "Apple Juice", Price = .5m,
                    Size = 10, Type = BeverageType.Juice},
                new Beverage {Name = "Grape Juice", Price = .5m,
                    Size = 10, Type = BeverageType.Juice},
                new Beverage {Name = "Water", Price = .25m,
                    Size = 20, Type = BeverageType.Water},
                new Beverage {Name = "Beer", Price = 2.75m,
                    Size = 16, Type = BeverageType.Alcohol},
                new Beverage {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;
            }

        }
    }


    {
        public enum BeverageType
        {
            Soda,
            Juice,
            Water,
            Alcohol
        }

        public class Beverage
        {
            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}) = {Price:C}";
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

IEnumerable<T>没有 添加 删除 方法。我们通常会继承List,除非您有特定要求使用IEnumerable<T>

例如,

class Crate : List<Beverage>
{
    public new void Add(Beverage beverage)
    {
        if (Count == 24)
        {
            Console.WriteLine("The crate is full. Please remove an item first!");
        }
        else
        {
            base.Add(beverage);
        }
    }

    public void Remove(string name)
    {
        Remove(this.FirstOrDefault(i => i.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
    }

    public void PrintCrate()
    {
        if (this.Count == 0)
        {
            Console.WriteLine("There are no items in the crate.");
        }
        else
        {
            this.ForEach(Console.WriteLine);
        }
    }
}

更新:从IEnumerable<T>继承

由于您必须按照要求使用 数组 ,因此您必须实施 添加 自行删除 方法。添加非常简单,但删除有点棘手。

class Crate : IEnumerable<Beverage>
{
    private Beverage[] crate = new Beverage[24];
    private int NumberOfBottles = 0;
    private const int MaxItems = 24;

    public void Add(Beverage beverage)
    {
        if (NumberOfBottles >= MaxItems)
        {
            Console.WriteLine("The crate is full. Please remove an item first!");
        }
        else
        {
            crate[NumberOfBottles] = beverage;
            NumberOfBottles++;
        }
    }

    public IEnumerator<Beverage> GetEnumerator()
    {
        return crate.AsEnumerable().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Remove(string name)
    {
        Remove(crate.FirstOrDefault(i =>
            i.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
    }

    public void Remove(Beverage 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(Beverage);
        }
    }

    public void PrintCrate()
    {
        if (NumberOfBottles == 0)
        {
            Console.WriteLine("There are no items in the crate.");
        }
        else
        {
            foreach (var beverage in this)
                Console.WriteLine(beverage);
        }
    }
}