用户对象输入到数据列表中

时间:2017-07-12 16:59:23

标签: c# arrays list collections

我有一个程序试图创建一个典型的汽水箱程序,用户可以从列表中选择并添加到24的数组中,以表示汽水箱。但我希望它打印出这里的对象列表,以检查我的代码是否在我继续之前没有被破坏。除非我无法打印出数据。我尝试使用foor循环,但它没有工作

public class BeverageData
{
      public string Name { set; get; }
      public string Type { set; get; }
      public decimal Price { set; get; }
      public int Size { get; set; }
}

class Beverages : IEnumerable<BeverageData>
{
    public static void BeverageRun()
    {
        var crate = new List<BeverageData>();

        //Add some items to it
        var newBeverage= new BeverageData();
        newBeverage.Name = "Fanta";
        newBeverage.Price = 0.75M;
        newBeverage.Type = "Soda";
        crate.Add(newBeverage);

        crate.Add(new BeverageData() { Name = "Pepsi", Price = 0.25M, Type = "Soda" });

        //Prompting the user


        crate.Add(PromptUserForBeverage());

        foreach (var beverage in crate)
        {
            Console.WriteLine(beverage);
        }
    }

    public void RemoveBeverage(string name)
    {

        var beverages = (from i in _items where String.Compare(i.Name, name, true) == 0 select i).FirstOrDefault();

        if (beverages != null)
            _items.Remove(beverages);
    }
    public IEnumerator<BeverageData> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

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

    private readonly List<BeverageData> _items = new List<BeverageData>();

    static BeverageData PromptUserForBeverage()
    {
        var beverage = new BeverageData();

        Console.WriteLine("Enter name: ");
        beverage.Name = Console.ReadLine();

        beverage.Price = GetDecimal("Enter cost: ");

        Console.WriteLine("Enter type: ");
        beverage.Type = Console.ReadLine();

        return beverage;
    }

    static decimal GetDecimal(string message)
    {
        do
        {
            Console.WriteLine(message);
            var input = Console.ReadLine();

            decimal result;
            if (Decimal.TryParse(input, out result))
                return result;

            Console.WriteLine("Invalid number");
        } while (true);
    }
}

主类的编辑:

public static object MyProperty
        {
            get { return beverages; }
            set { beverages = new Crate}
        }
        static void Main(string[] args)
        {
            //var beverages = new Crate();
            ShowMenu();
            // Wait for input before closing
            Console.WriteLine("\nDone!\nPress any key to exit...");
            Console.ReadKey();
        }
        public static void ShowMenu()
        {
            Console.WriteLine("[1] Add Bottle from existing list to Bottle Crate");
            Console.WriteLine("[2] Remove Bottle from Bottle Crate");
            Console.WriteLine("[3] Show Bottle Crate");
            Console.WriteLine("[4] Add Beverage to list");
            Console.WriteLine("[5] Remove Beverage from list");
            Console.WriteLine("[6] Sort Bottles in Bottle Crate");
            Console.WriteLine("[7] Sort Beverages in list");

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

            switch (selection)
            {
                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(Crate.GetBeverageFromUser());
                        Console.WriteLine("-----------------------\n");
                    }
                    numBevs = Math.Max(GetInt("How many would you like to be auto-added: "), 0);

                    for (int i = 0; i < numBevs; i++)
                    {
                        beverages.Add(Crate.GetRandomBeverage());
                    }
                    Console.WriteLine("-----------------------\n");
                    ShowMenu();
                    break;
                //case 2:
                //    Remove_Bottle();
                //    ShowMenu();
                //    break;
                case 3:
                    Console.WriteLine("\nHere are the contents of the crate:\n");
                    Console.ForegroundColor = ConsoleColor.Green;
                    beverages.PrintBeverages();
                    Console.ResetColor();
                    ShowMenu();
                    break;
                //case 4:
                //    BeverageRun();
                //    ShowMenu();
                //    break;
                //case 5:
                //    Remove_Beverage();
                //    ShowMenu();
                //    break;
                //case 6:
                //    Sort_Bottles();
                //    ShowMenu();
                //    break;
                //case 7:
                //    Sort_Beverages();
                //    ShowMenu();
                //    break;
                //case 8:
                //    Calc_Total();
                //    ShowMenu();
                //    break;
                case 9:
                    break;
                default:
                    ShowMenu();
                    break;
            }

        }
    }
}

3 个答案:

答案 0 :(得分:5)

public static void BeverageRun()
{
    var crate = new List<BeverageData>();

    //Add some items to it
    var newBeverage= new BeverageData();
    newBeverage.Name = "Fanta";
    newBeverage.Price = 0.75M;
    newBeverage.Type = "Soda";

    crate.Add(newBeverage);
    crate.Add(new BeverageData() { Name = "Pepsi", Price = 0.25M, Type = "Soda" });

    //Prompting the user
    crate.Add(PromptUserForBeverage());

    foreach (var beverage in crate)
    {
        PrintBeverage(beverage);
    }
}

static string PrintBeverage(BeverageData beverage)
{
    Console.WriteLine("Name: " + beverage.Name + ", Price: $" + beverage.Price + ", Type: " + beverage.Type);
}

我假设您打算遍历crate列表。但是,这样做会打印饮料对象。不是饮料的价值。因此,如果您想查看饮料的价值,您可能需要更改它。

修改

如上所述Ed Plunkett,您也可以覆盖ToString()的{​​{1}}。这样做会是这样的。

BeverageData

在foreach循环中:

public class BeverageData
{
    public string Name { set; get; }
    public string Type { set; get; }
    public decimal Price { set; get; }
    public int Size { get; set; }

    public override string ToString()
    {
        return "Name: " + Name + ", Price: $" + Price + ", Type: " + Type;
    }
}

答案 1 :(得分:0)

您正在尝试打印新创建的列表(零项目)的项目。不出所料,没有任何印刷品。

答案 2 :(得分:-1)

问题是您要将项目添加到本地列表(crate)而不是类级别列表(_items)。

您可能遇到的其他几个问题是您允许为饮料类型输入字符串,这意味着用户输入可能存在一些错误(有些可能会说“苏打”,有些可能会说“流行”有些人可能会说“软饮料”)。要解决此问题,您可以为此字段使用enum预定义类型:

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

我注意到的另一件事是你没有向Add项目提供方法到箱子里,只提供给Remove他们,所以我在下面添加了。我还添加了另一个Remove方法,该方法将删除Beverage类型,该类型现在从原始移动方法中调用。

我们也错过了MaxCapacity功能 - 您说过一个箱子只能容纳24件物品,但我们并没有在任何地方强制执行。现在,当有人调用Add方法时,如果包装箱已满,它会显示一条消息,并且他们必须先删除一些内容。

我还从PrintItems方法中分离出BeverageRun方法,并将BeverageRun更改为AddBeverageFromUser,因为我觉得它做得太多了 - 它是添加一些预定义的饮料,从用户那里获取一个,然后打印出来。通常最好让方法做一件事。

我还添加了一个名为AddRandomBeverage的方法,因此我们可以自动填充包,而不必强迫用户进行这么多的输入。

最后,我添加了GetStringGetBeverageType方法,以赞美您的GetDecimal方法,以便从用户那里获取强类型信息。

以下是最终Crate课程的出版方式:

class Crate : IEnumerable<Beverage>
{
    private readonly List<Beverage> crate = new List<Beverage>();
    private const int MaxItems = 24;
    private static readonly Random Rnd = new Random();

    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 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 PrintBeverages()
    {
        if (crate.Count == 0)
        {
            Console.WriteLine("There are no items in the crate.");
        }
        else
        {
            crate.ForEach(Console.WriteLine);
        }
    }

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

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

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

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

<强>用法

Crate类的用法可能如下所示:

private static void Main()
{
    var beverages = new Crate();

    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(Crate.GetBeverageFromUser());
        Console.WriteLine("-----------------------\n");
    }

    numBevs = Math.Max(GetInt("How many would you like to be auto-added: "), 0);

    for (int i = 0; i < numBevs; i++)
    {
        beverages.Add(Crate.GetRandomBeverage());
    }
    Console.WriteLine("-----------------------\n");

    Console.WriteLine("\nHere are the contents of the crate:\n");
    Console.ForegroundColor = ConsoleColor.Green;
    beverages.PrintBeverages();
    Console.ResetColor();

    // Wait for input before closing
    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

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

<强>输出

enter image description here