是否只有在使用时才打印出一行文本?

时间:2019-06-07 09:10:05

标签: c# console-application

link to full code

我正在创建一个小型咖啡馆应用程序。在提示用户输入详细信息,输入他们要订购的商品代码和数量后,我希望仅在订购的账单中获得打印输出。

tl; dr:我希望帐单仅在他们订购了芝士蛋糕时才打印出订购的(例如)芝士蛋糕的详细信息,我不希望其他菜单项出现在帐单上。

我已经手动打印了应用程序的标题。然后,我将其置于if条件下,以查看是否正在执行某个功能,以及是否要分别打印详细信息(例如:如果您订购了3个芝士蛋糕,它将在帐单上打印其详细信息。)

Console.WriteLine("|    Item Code   |" + "|    Item Name    |" + "|    Item Cost    |" + "|     Qty Ordered     |");

double totBillCost = 0;
            if (makeOrder.orderCode == 1)
            {
                totBillCost = totBillCost + (cheesecake.itemCost * makeOrder.orderQty);
                Console.WriteLine("      "+ cheesecake.itemCode + "      " + cheesecake.itemName + "      " + cheesecake.itemCost + "      " + makeOrder.orderQty);
        }

我希望这是有道理的。我基本上希望它在订购时输出一份芝士蛋糕的详细信息。

如果重要的话,菜单上总共有4个项目。

1 个答案:

答案 0 :(得分:1)

尝试类似的东西:

class Program
{
    static void Main(string[] args)
    {
        List<ISellable> boughtItems = new List<ISellable>
        {
            new BottleOfWater(),
            new Sugar(),
            new Chocolate(),
            new Sugar(),
            new BottleOfWater(),
            new BottleOfWater(),
            new BottleOfWater(),
            new BottleOfWater(),
            new BottleOfWater()
        };

        Console.WriteLine("| Name | Price | Amount |");

        List<IGrouping<Type, ISellable>> groupedBoughtItems = boughtItems.GroupBy(x => x.GetType()).ToList();

        foreach(IGrouping<Type, ISellable> group in groupedBoughtItems)
        {
            Console.WriteLine(string.Format("| {0} | {1} | {2} |", group.First().Name, group.First().Price, group.Count()));
        }

        Console.WriteLine(string.Format("| Total | {0} |", boughtItems.Sum(x => x.Price)));
    }
}

public interface ISellable
{
    string Name { get; set; }
    double Price { get; set; }
}

public class BottleOfWater : ISellable
{
    public string Name { get; set; }
    public double Price { get; set; }

    public BottleOfWater()
    {
        Name = "Bottle Of Water";
        Price = 2.55;
    }
}

public class Sugar : ISellable
{
    public string Name { get; set; }
    public double Price { get; set; }

    public Sugar()
    {
        Name = "Sugar";
        Price = 1.3;
    }
}

public class Chocolate : ISellable
{
    public string Name { get; set; }
    public double Price { get; set; }

    public Chocolate()
    {
        Name = "Chocolate";
        Price = 50;
    }
}