Как я могу получить свой код для вывода общей цены продаж пользователей? - PullRequest
1 голос
/ 06 октября 2019

В настоящее время я пытаюсь создать небольшую программу для торговых автоматов, в которой пользователь выбирает товар, спрашивает, сколько ему нужно этого товара, затем находит общую цену продавца и дает им правильное количество изменений. Я, кажется, не могу получить этот код для вывода общей цены вендора. Может кто-нибудь сказать мне, где я иду не так?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ugh
{
  class Program
  {
    struct VendingItem
    {
        public string name;
        public double price;
        public string code;
    }
    static void Main(string[] args)
    {
        string selection = "";
        double price = 0;
        double finalCost = 0;
        int numOfItem = 0;
        bool Yorn = true;
        Dictionary<string, VendingItem> snacks = new Dictionary<string, VendingItem>();
        VendingItem v;

        //snacks
        v.name = "Mars Bar";
        v.price = 1.30;
        v.code = "A1";
        snacks.Add(v.code, v);

        v.name = "Milky Way";
        v.price = 1.30;
        v.code = "A2";
        snacks.Add(v.code, v);

        v.name = "Double Decker";
        v.price = 1.30;
        v.code = "A3";
        snacks.Add(v.code, v);

        v.name = "Kit Kat";
        v.price = 1.30;
        v.code = "A4";
        snacks.Add(v.code, v);

        v.name = "Dairy Milk";
        v.price = 1.30;
        v.code = "A5";
        snacks.Add(v.code, v);

        v.name = "Pringles Original";
        v.price = 1.70;
        v.code = "A6";
        snacks.Add(v.code, v);

        v.name = "Pringles Salt and Vinegar";
        v.price = 1.70;
        v.code = "A7";
        snacks.Add(v.code, v);

        v.name = "Pringles Cheese and Onion";
        v.price = 1.70;
        v.code = "A8";
        snacks.Add(v.code, v);

        v.name = "Pringles Texas BBQ";
        v.price = 1.70;
        v.code = "A9";
        snacks.Add(v.code, v);

        v.name = "Pringles Prawn Cocktail";
        v.price = 1.70;
        v.code = "A10";
        snacks.Add(v.code, v);

        //drinks

        v.name = "Water";
        v.price = 1.00;
        v.code = "A11";
        snacks.Add(v.code, v);

        v.name = "Red Bull";
        v.price = 1.35;
        v.code = "A12";
        snacks.Add(v.code, v);

        v.name = "Monster";
        v.price = 1.35;
        v.code = "A13";
        snacks.Add(v.code, v);

        v.name = "Fanta Orange";
        v.price = 1.20;
        v.code = "A14";
        snacks.Add(v.code, v);

        v.name = "Fanta Fruit Twist";
        v.price = 1.20;
        v.code = "A15";
        snacks.Add(v.code, v);
        //outputting the name, code and price of each item in the list
        foreach (KeyValuePair<string, VendingItem> item in snacks)
        {
            Console.WriteLine("Snack: {0} -\nCode: {1}\nPrice: £{2}\n\n", item.Value.name, item.Value.code, item.Value.price);
        }            
        //calling the vendSelection method using a new string selection and the dictionary snacks as the parameters
        vendSelection(selection, snacks);
        //find out how many they would like
        Console.WriteLine("How many of this item would you like?");
        numOfItem = int.Parse(Console.ReadLine());

        //get the price of item at location of user selection
        foreach (KeyValuePair<string, VendingItem> item in snacks)
        {
            price = item.Value.price.CompareTo(item.Value.code.CompareTo(selection));
        }
        totalPrice(price, numOfItem);
        Console.WriteLine(price);

        Console.ReadLine();
    }                  
    //method for taking user input and comparing it to the code of the snack/drink
    static string vendSelection(string x, Dictionary<string, VendingItem> snacks)
    {
       Console.WriteLine("Please enter the code that corresponds with the item you would like: ");
       x = Console.ReadLine();
       bool YorN = true;           
       while (YorN == true)
       {             
           if (snacks.ContainsKey(x))
           {                                     
               YorN = false;                    
           }
           else
           {
               Console.WriteLine("That is not an item in the list. Please enter another selection: ");
               x = Console.ReadLine();
           }               
       }
       return x;
    }
    //method for calculating price
    static double totalPrice(double price, int number)
    {
        return price * number;
    }
  }
}

Я пытаюсь получить вывод любой суммыбудет, но вместо этого все, что я получу, это номер элемента, который я ввел, кто-нибудь может предложить способ решить эту проблему?

1 Ответ

1 голос
/ 06 октября 2019

Ваше решение слишком сложное и немного трудное для чтения, поэтому я переписал его. Попробуйте это вместо этого. Я удалил несколько ненужных объявлений и методов и получил рабочее решение для вас. Любые вопросы, просто задавайте.

public class Program
{
    public struct VendingItem
    {
        public string name;
        public double price;
        public string code;
    }

    static void Main(string[] args)
    {
        List<VendingItem> stockCatalog = CatalogData();

        // Show the catalog to the user
        stockCatalog.ForEach(i => {
            Console.WriteLine($"Snack: {i.name}, Code: {i.code}, Price: £{i.price}");
        });

        // Get an item selection from the user
        VendingItem selection = GetSelection(stockCatalog);

        // Get a quantity from the user
        Console.WriteLine("How many of this item would you like?");
        int numOfItem = int.Parse(Console.ReadLine());

        double totalValue = selection.price * numOfItem;
        Console.WriteLine($"Your total cost is {totalValue}.");

        Console.ReadLine();
    }

    // Get a selection from the user, if the user selection doesn't match an item in the catalog, ask again until it does.
    static VendingItem GetSelection(List<VendingItem> vendingItems)
    {
        Console.WriteLine("Please enter the code that corresponds with the item you would like: ");
        string itemCode = Console.ReadLine();

        if (vendingItems.Any(i => i.code == itemCode))
        {
            return vendingItems.First(i => i.code == itemCode);
        }
        else
        {
            Console.WriteLine("That is not an item in the list.");
            return GetSelection(vendingItems);
        }

    }

    public static List<VendingItem> CatalogData()
    {
        List<VendingItem> vendingItems = new List<VendingItem>();

        // Add food items
        vendingItems.Add(new VendingItem { code = "A1", price = 1.30, name = "Mars Bar" });
        vendingItems.Add(new VendingItem { code = "A2", price = 1.30, name = "Milky Way" });
        vendingItems.Add(new VendingItem { code = "A3", price = 1.30, name = "Double Decker" });
        vendingItems.Add(new VendingItem { code = "A4", price = 1.30, name = "Kit Kat" });
        vendingItems.Add(new VendingItem { code = "A5", price = 1.30, name = "Dairy Milk" });
        vendingItems.Add(new VendingItem { code = "A6", price = 1.70, name = "Pringles Original" });
        vendingItems.Add(new VendingItem { code = "A7", price = 1.70, name = "Pringles Salt and Vinegar" });
        vendingItems.Add(new VendingItem { code = "A8", price = 1.70, name = "Pringles Cheese and Onion" });
        vendingItems.Add(new VendingItem { code = "A9", price = 1.70, name = "Pringles Texas BBQ" });
        vendingItems.Add(new VendingItem { code = "A10", price = 1.70, name = "Pringles Prawn Cocktail" });

        // Add drink items
        vendingItems.Add(new VendingItem { code = "A11", price = 1.00, name = "Water" });
        vendingItems.Add(new VendingItem { code = "A12", price = 1.35, name = "Red Bull" });
        vendingItems.Add(new VendingItem { code = "A13", price = 1.35, name = "Monster" });
        vendingItems.Add(new VendingItem { code = "A14", price = 1.20, name = "Fanta Orange" });
        vendingItems.Add(new VendingItem { code = "A15", price = 1.20, name = "Fanta Fruit Twist" });

        // Send back the catalog collection
        return vendingItems;
    }
}

Использование словаря ..

public class Program
{
    public struct VendingItem
    {
        public string name;
        public double price;
        public string code;
    }

    static void Main(string[] args)
    {
        Dictionary<string, VendingItem> stockDictionary = CatalogDataDictionary();

        // Show the catalog to the user
        foreach (KeyValuePair<string, VendingItem> i in stockDictionary)
        {
            Console.WriteLine($"Snack: {i.Value.name}, Code: {i.Value.code}, Price: £{i.Value.price}");
        }

        // Get an item selection from the user
        VendingItem selection = GetSelection(stockDictionary);

        // Get a quantity from the user
        Console.WriteLine("How many of this item would you like?");
        int numOfItem = int.Parse(Console.ReadLine());

        double totalValue = selection.price * numOfItem;
        Console.WriteLine($"Your total cost is {totalValue}.");

        Console.ReadLine();
    }

    // Get a selection from the user, if the user selection doesn't match an item in the catalog, ask again until it does.
    static VendingItem GetSelection(Dictionary<string, VendingItem> vendingItems)
    {
        Console.WriteLine("Please enter the code that corresponds with the item you would like: ");
        string itemCode = Console.ReadLine();

        if (vendingItems.ContainsKey(itemCode))
        {
            return vendingItems.First(i => i.Key == itemCode).Value;
        }
        else
        {
            Console.WriteLine("That is not an item in the list.");
            return GetSelection(vendingItems);
        }

    }

    public static Dictionary<string, VendingItem> CatalogDataDictionary()
    {
        Dictionary<string, VendingItem> keyValuePairs = new Dictionary<string, VendingItem>();

        // Add the food items
        keyValuePairs.Add("A1", new VendingItem() { code = "A1", price = 1.30, name = "Mars Bar" });

        return keyValuePairs;
    }
}

В обоих примерах процесс получения нескольких предметов является чрезмерно упрощенным и склонным к бросаниюошибки, если пользователь вводит нечисловое значение. В действительности вы должны использовать метод, аналогичный GetSelection(), который возвращает INT, и использовать этот метод для проверки того, что ввод является допустимым числовым значением (min, max и т. Д.), Прежде чем передать его обратно в основной метод.

Для целей базовой демонстрации достаточно вышеприведенного.

...