Exemplo n.º 1
0
        /// <summary>
        /// Adds an item to the vending machine
        /// </summary>
        /// <param name="line">The line of text in the input file.</param>
        /// <param name="inventory">The inventory in the vending machine.</param>
        private void AddNewItemToVendingMachine(string line, Dictionary <string, VendingMachineItem> inventory)
        {
            string[] fields = line.Split('|');

            const int slotColumn  = 0; // fields[0] is the slot
            const int nameColumn  = 1; // fields[1] is the name
            const int priceColumn = 2; // fields[2] is the price
            const int typeColumn  = 3; // fields[3] is the type

            if (fields[typeColumn] == "Gum")
            {
                Gum gum = new Gum(fields[slotColumn], fields[nameColumn], decimal.Parse(fields[priceColumn]), fields[typeColumn]);
                inventory.Add(fields[slotColumn], gum);
            }
            else if (fields[typeColumn] == "Chip")
            {
                Chip chip = new Chip(fields[slotColumn], fields[nameColumn], decimal.Parse(fields[priceColumn]), fields[typeColumn]);
                inventory.Add(fields[slotColumn], chip);
            }
            else if (fields[typeColumn] == "Candy")
            {
                Candy candy = new Candy(fields[slotColumn], fields[nameColumn], decimal.Parse(fields[priceColumn]), fields[typeColumn]);
                inventory.Add(fields[slotColumn], candy);
            }
            else if (fields[typeColumn] == "Drink")
            {
                Drink drink = new Drink(fields[slotColumn], fields[nameColumn], decimal.Parse(fields[priceColumn]), fields[typeColumn]);
                inventory.Add(fields[slotColumn], drink);
            }
        }
Exemplo n.º 2
0
        public StockService()
        {
            string productFile       = @"../../../etc/vendingmachine.csv";
            bool   productFileExists = File.Exists(productFile);

            if (productFileExists)
            {
                try
                {
                    List <string> productStreamList = new List <string>();

                    // Get products from a stream and save them to productStreamList
                    using (StreamReader sR = new StreamReader(productFile))
                    {
                        while (!sR.EndOfStream)
                        {
                            string productStream = sR.ReadLine();
                            productStreamList.Add(productStream);
                        }
                    }

                    //Go thru productStreamList and creat products
                    foreach (var productStreamLine in productStreamList)
                    {
                        List <string> productProps = productStreamLine.Split('|').ToList();
                        Product       newProduct   = null;

                        switch (productProps[0].Substring(0, 1))
                        {
                        case "A":
                            newProduct = new Chip(productProps[0], productProps[1], double.Parse(productProps[2]), 5);
                            break;

                        case "B":
                            newProduct = new Candy(productProps[0], productProps[1], double.Parse(productProps[2]), 5);
                            break;

                        case "C":
                            newProduct = new Drinks(productProps[0], productProps[1], double.Parse(productProps[2]), 5);
                            break;

                        case "D":
                            newProduct = new Gum(productProps[0], productProps[1], double.Parse(productProps[2]), 5);
                            break;
                        }

                        Products.Add(newProduct);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Sorry...Vendo is currently experienceing some technical diffculties:");
                    Console.WriteLine(e.Message);
                }
            }
            else
            {
                Console.WriteLine("Vendo-Matic 500 down for Maintenance");
            }
        }
Exemplo n.º 3
0
        //Creates Vending Machine Objects
        public void CreateVendingItem(string vendingData)
        {
            string[]           vendingInfo        = vendingData.Split("|");
            string             itemKey            = vendingInfo[0];
            string             itemName           = vendingInfo[1];
            decimal            itemPrice          = decimal.Parse(vendingInfo[2]);
            string             itemType           = vendingInfo[3];
            VendingMachineItem vendingMachineItem = null;

            if (itemType == "Chip")
            {
                vendingMachineItem = new Chip(itemName, itemPrice);
            }
            else if (itemType == "Gum")
            {
                vendingMachineItem = new Gum(itemName, itemPrice);
            }
            else if (itemType == "Drink")
            {
                vendingMachineItem = new Drink(itemName, itemPrice);
            }
            else if (itemType == "Candy")
            {
                vendingMachineItem = new Candy(itemName, itemPrice);
            }
            _inventory.Add(itemKey, vendingMachineItem);
        }
Exemplo n.º 4
0
        private IVendingItem GetItemFromItemPart(char firstCharacter)
        {
            IVendingItem item = null;

            switch (firstCharacter)
            {
            case 'A':
                item = new Chips();
                break;

            case 'B':
                item = new Candy();
                break;

            case 'C':
                item = new Drink();
                break;

            case 'D':
                item = new Gum();
                break;
            }

            return(item);
        }
Exemplo n.º 5
0
        // string is going to equal the itemCode
        // VendingItem will equal all the other values

        public Dictionary <string, VendingItem> ImportingVendingItems()
        {
            Dictionary <string, VendingItem> vendingItems = new Dictionary <string, VendingItem>();

            string directory = @"..\..\..\..";
            string fileName  = "vendingmachine.csv";
            string fullPath  = Path.Combine(directory, fileName);


            try
            {
                using (StreamReader sr = new StreamReader(fullPath))
                {
                    while (!sr.EndOfStream)
                    {
                        string   line           = sr.ReadLine();
                        string[] itemSection    = line.Split("|");
                        string   itemName       = itemSection[1];
                        decimal  itemPrice      = decimal.Parse(itemSection[2]);
                        int      itemsRemaining = 5;

                        VendingItem itemType;   // call new variable itemType

                        switch (itemSection[3]) // switch out type with all the values
                        {
                        case "Beverages":
                            itemType = new Beverages(itemName, itemPrice, itemsRemaining);
                            break;

                        case "Candy":
                            itemType = new Candy(itemName, itemPrice, itemsRemaining);
                            break;

                        case "Chips":
                            itemType = new Chips(itemName, itemPrice, itemsRemaining);
                            break;

                        case "Gum":
                            itemType = new Gum(itemName, itemPrice, itemsRemaining);
                            break;

                        default:     // don't forget this
                            itemType = new Gum(itemName, itemPrice, itemsRemaining);
                            break;
                        }

                        vendingItems.Add(itemSection[0], value: itemType);
                    }
                }
            }
            catch
            {
                Console.WriteLine("Can't import CSV.");
            }

            return(vendingItems); // updated dictionary
        }
Exemplo n.º 6
0
        //Method to run to stock the inventory on machine startup
        public void StockInventory()
        {
            string         slotLocation;
            string         name;
            decimal        price;
            string         type;
            string         pathToInventoryFile = Path.Combine(Directory.GetCurrentDirectory(), "vendingmachine.csv");
            Queue <string> linesOfItems        = new Queue <string>();

            //Pulls file containing what items to add to the vending machine
            try
            {
                using (StreamReader sr = new StreamReader(pathToInventoryFile))
                {
                    while (!sr.EndOfStream)
                    {
                        linesOfItems.Enqueue(sr.ReadLine());
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Sorry something went wrong while stocking items");
            }

            //Creates each item pulled from the file and creates them as the correct object depending on the type of the item
            while (linesOfItems.Count > 0)
            {
                string[] individualItemInfo = linesOfItems.Dequeue().Split('|');
                slotLocation = individualItemInfo[0];
                name         = individualItemInfo[1];
                price        = decimal.Parse(individualItemInfo[2]);
                type         = individualItemInfo[3];

                if (type == "Chip")
                {
                    Chip chip = new Chip(name, price, 5);
                    listOfItems.Add(slotLocation, chip);
                }
                else if (type == "Candy")
                {
                    Candy candy = new Candy(name, price, 5);
                    listOfItems.Add(slotLocation, candy);
                }
                else if (type == "Drink")
                {
                    Drink drink = new Drink(name, price, 5);
                    listOfItems.Add(slotLocation, drink);
                }
                else if (type == "Gum")
                {
                    Gum gum = new Gum(name, price, 5);
                    listOfItems.Add(slotLocation, gum);
                }
            }
        }
Exemplo n.º 7
0
        public Dictionary <string, VendingMachineItems> DisplayInventory()
        {
            Dictionary <string, VendingMachineItems> itemsInventory = new Dictionary <string, VendingMachineItems>();
            string directory = Directory.GetCurrentDirectory();
            string fileName  = "vendingmachine.csv";
            string fullPath  = Path.Combine(directory, fileName);

            using (StreamReader sr = new StreamReader(fullPath))
            {
                while (!sr.EndOfStream)
                {
                    string   line      = sr.ReadLine();
                    string[] lineSplit = line.Split("|");
                    foreach (string lines in lineSplit)
                    {
                        if (lineSplit[3] == "Chip")
                        {
                            Chip chip = new Chip();
                            chip.Name     = lineSplit[1];
                            chip.Price    = Convert.ToDecimal(lineSplit[2]);
                            chip.Quantity = 5;
                            itemsInventory.Add(lineSplit[0], chip);
                            break;
                        }
                        if (lineSplit[3] == "Gum")
                        {
                            Gum gum = new Gum();
                            gum.Name     = lineSplit[1];
                            gum.Price    = Convert.ToDecimal(lineSplit[2]);
                            gum.Quantity = 5;
                            itemsInventory.Add(lineSplit[0], gum);
                            break;
                        }
                        if (lineSplit[3] == "Drink")
                        {
                            Drink drink = new Drink();
                            drink.Name     = lineSplit[1];
                            drink.Price    = Convert.ToDecimal(lineSplit[2]);
                            drink.Quantity = 5;
                            itemsInventory.Add(lineSplit[0], drink);
                            break;
                        }
                        if (lineSplit[3] == "Candy")
                        {
                            Candy candy = new Candy();
                            candy.Name     = lineSplit[1];
                            candy.Price    = Convert.ToDecimal(lineSplit[2]);
                            candy.Quantity = 5;
                            itemsInventory.Add(lineSplit[0], candy);
                            break;
                        }
                    }
                }
            }
            return(itemsInventory);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Reads from VendingMachine.txt to add items to ItemList
        /// </summary>
        private void LoadInventory()
        {
            Dictionary <string, double> itemPrices = new Dictionary <string, double>();

            string directory = @"..\..\..\..\etc";
            string fileName  = "VendingMachine.txt";

            string fullPath = Path.Combine(directory, fileName);

            try
            {
                using (StreamReader sr = new StreamReader(fullPath))
                {
                    while (!sr.EndOfStream)
                    {
                        string   line       = sr.ReadLine();
                        string[] properties = line.Split('|');
                        string   slotId     = properties[0];

                        double itemPrice = double.Parse(properties[2]);
                        if (properties[3] == "Chip")
                        {
                            Chip chip = new Chip(properties[1], itemPrice);
                            ItemList.Add(slotId, chip);
                        }
                        if (properties[3] == "Candy")
                        {
                            Candy candy = new Candy(properties[1], itemPrice);
                            ItemList.Add(slotId, candy);
                        }
                        if (properties[3] == "drink")
                        {
                            Drink drink = new Drink(properties[1], itemPrice);
                            ItemList.Add(slotId, drink);
                        }
                        if (properties[3] == "Gum")
                        {
                            Gum gum = new Gum(properties[1], itemPrice);
                            ItemList.Add(slotId, gum);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw new CorruptInventoryException();
            }

            foreach (KeyValuePair <string, Item> item in ItemList)
            {
                string itemName  = item.Value.Name;
                double itemPrice = item.Value.Price;
                itemPrices.Add(itemName, itemPrice);
            }
            ItemPrices = itemPrices;
        }
Exemplo n.º 9
0
        private Gum CreateGum(string line)
        {
            string[] items = line.Split('|');
            string   name  = items[Col_Name];
            decimal  price = decimal.Parse(items[Col_Price]);

            Gum gum = new Gum(name, price);

            return(gum);
        }
        public void LoadInventory()
        {
            string sourceFilePath = "vendingmachine.csv";

            if (!Path.IsPathRooted(sourceFilePath))
            {
                sourceFilePath = Path.Combine(Environment.CurrentDirectory, sourceFilePath);
            }

            try
            {
                using (StreamReader sr = new StreamReader(sourceFilePath))
                {
                    while (!sr.EndOfStream)
                    {
                        string line      = sr.ReadLine();
                        char[] splitChar = { '|' };

                        string[] itemLoc = line.Split(splitChar);

                        if (itemLoc[3] == Item.Candy)
                        {
                            Candy         candy = new Candy(itemLoc[1], double.Parse(itemLoc[2]));
                            InventoryItem item  = new InventoryItem(candy);
                            _inventory.Add(itemLoc[0], item);
                        }
                        if (itemLoc[3] == Item.Chips)
                        {
                            Chips         chip = new Chips(itemLoc[1], double.Parse(itemLoc[2]));
                            InventoryItem item = new InventoryItem(chip);
                            _inventory.Add(itemLoc[0], item);
                        }
                        if (itemLoc[3] == Item.Beverage)
                        {
                            Beverage      drink = new Beverage(itemLoc[1], double.Parse(itemLoc[2]));
                            InventoryItem item  = new InventoryItem(drink);
                            _inventory.Add(itemLoc[0], item);
                        }
                        if (itemLoc[3] == Item.Gum)
                        {
                            Gum           gum  = new Gum(itemLoc[1], double.Parse(itemLoc[2]));
                            InventoryItem item = new InventoryItem(gum);
                            _inventory.Add(itemLoc[0], item);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Exemplo n.º 11
0
        public void ReadFile(Dictionary <string, Product> mainMenu)
        {
            string directory = Directory.GetCurrentDirectory();
            string filename  = "vendingmachine.csv";
            string path      = Path.Combine(directory, filename);


            try
            {
                using (StreamReader sr = new StreamReader(path))
                {
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();

                        string[] productArray = line.Split('|');
                        slot  = productArray[0];
                        name  = productArray[1];
                        price = decimal.Parse(productArray[2]);
                        type  = productArray[3];


                        if (type == "Chip")
                        {
                            Chip chipName = new Chip(price, name, qty);
                            mainMenu.Add(slot, chipName);
                        }
                        else if (type == "Candy")
                        {
                            Candy candyName = new Candy(price, name, qty);
                            mainMenu.Add(slot, candyName);
                        }
                        else if (type == "Gum")
                        {
                            Gum gumName = new Gum(price, name, qty);
                            mainMenu.Add(slot, gumName);
                        }
                        else if (type == "Drink")
                        {
                            Drink drinkName = new Drink(price, name, qty);
                            mainMenu.Add(slot, drinkName);
                        }
                    }
                }
            }catch (Exception e)
            {
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Stocks or vending machine using the csv file
        /// </summary>
        /// <param name="stock"></param>
        public static void StockVendingMachine(Dictionary <string, Item> stock)
        {
            // Directory and file name
            string directory = Environment.CurrentDirectory;
            string filename  = "vendingmachine.csv";

            // Full Path
            string fullPath = Path.Combine(directory, "..\\..\\..\\..\\etc", filename);

            // Here we'll read in the file, separate each word with a comma and store
            // the individual word in a collection.
            try
            {
                using (StreamReader sr = new StreamReader(fullPath))
                {
                    while (!sr.EndOfStream)
                    {
                        int      maxAmount = (5);
                        string   line      = sr.ReadLine();
                        string[] words     = line.Split('|');
                        string   snackType = words[3];
                        if (snackType == "Chip")
                        {
                            stock[words[0]] = new Chip(words[0], words[1], decimal.Parse(words[2]), words[3], maxAmount);
                        }
                        if (snackType == "Candy")
                        {
                            stock[words[0]] = new Candy(words[0], words[1], decimal.Parse(words[2]), words[3], maxAmount);
                        }
                        if (snackType == "Drink")
                        {
                            stock[words[0]] = new Drink(words[0], words[1], decimal.Parse(words[2]), words[3], maxAmount);
                        }
                        if (snackType == "Gum")
                        {
                            stock[words[0]] = new Gum(words[0], words[1], decimal.Parse(words[2]), words[3], maxAmount);
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("Error reading the file");
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 13
0
        public VendingMachine()
        {
            Balance    = 0.00M;
            ReadError  = "";
            WriteError = "";

            try
            {
                using (StreamReader sr = new StreamReader(Path.Combine(filePath, inFile))) // Read input file and stock machine, i.e., populate list(items) with all snacks
                {
                    while (!sr.EndOfStream)
                    {
                        string   line      = sr.ReadLine();
                        string[] snackData = line.Split('|');

                        if (snackData[0][0] == 'A')
                        {
                            Chips chips = new Chips(snackData);
                            items.Add(chips);
                        }
                        else if (snackData[0][0] == 'B')
                        {
                            Candy candy = new Candy(snackData);
                            items.Add(candy);
                        }
                        else if (snackData[0][0] == 'C')
                        {
                            Drinks drink = new Drinks(snackData);
                            items.Add(drink);
                        }
                        else if (snackData[0][0] == 'D')
                        {
                            Gum gum = new Gum(snackData);
                            items.Add(gum);
                        }
                    }
                }
            }
            catch (IOException e) // Catch file read error
            {
                ReadError = "Error stocking the vending machine.\n" + e.Message;
            }
        }
Exemplo n.º 14
0
        public VendingMachine()
        {
            string directory = Environment.CurrentDirectory;
            string fileName  = "vendingmachine.csv";
            string fullPath  = Path.Combine(directory, fileName);

            try
            {
                using (StreamReader sr = new StreamReader(fullPath))
                {
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();

                        string[] itemArray = line.Split('|');

                        if (itemArray[0].StartsWith("A"))
                        {
                            vendingDictionary[itemArray[0]] = new Chips(itemArray[1], 5, double.Parse(itemArray[2]));
                        }
                        else if (itemArray[0].StartsWith("B"))
                        {
                            vendingDictionary[itemArray[0]] = new Candy(itemArray[1], 5, double.Parse(itemArray[2]));
                        }
                        else if (itemArray[0].StartsWith("C"))
                        {
                            vendingDictionary[itemArray[0]] = new Soda(itemArray[1], 5, double.Parse(itemArray[2]));
                        }
                        else
                        {
                            vendingDictionary[itemArray[0]] = new Gum(itemArray[1], 5, double.Parse(itemArray[2]));
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("There's an error!");
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 15
0
        public void Start()
        {
            //StreamReader to update vendingmachine parameters

            using (StreamReader sr = new StreamReader($"{fullpath}\\VendingMachine.txt"))
            {
                while (!sr.EndOfStream)
                {
                    string   line    = sr.ReadLine().Replace("|", ", ");
                    string[] product = line.Split(", ");
                    //update string for Display()
                    productData.Add($"{product[0]} {product[1]} {product[2]}");
                    //write dictionary values
                    if (product[3] == "Gum")
                    {
                        Item foodProduct = new Gum(product[1], decimal.Parse(product[2]));
                        Slot foodSlot    = new Slot(foodProduct, 5);
                        Inventory.Add(product[0], foodSlot);
                    }
                    else if (product[3] == "Chip")
                    {
                        Item foodProduct = new Chip(product[1], decimal.Parse(product[2]));
                        Slot foodSlot    = new Slot(foodProduct, 5);
                        Inventory.Add(product[0], foodSlot);
                    }
                    else if (product[3] == "Drink")
                    {
                        Item foodProduct = new Drink(product[1], decimal.Parse(product[2]));
                        Slot foodSlot    = new Slot(foodProduct, 5);
                        Inventory.Add(product[0], foodSlot);
                    }
                    else if (product[3] == "Candy")
                    {
                        Item foodProduct = new Candy(product[1], decimal.Parse(product[2]));
                        Slot foodSlot    = new Slot(foodProduct, 5);
                        Inventory.Add(product[0], foodSlot);
                    }
                }
            }
        }
        /// <summary>
        /// Slot Constructor
        /// </summary>
        /// <param name="rawTextLine">String line seperated by pipe (|) characters</param>
        public Slot(string rawTextLine)
        {
            //set quantity to 5
            Quantity = 5;

            //Split raw line text
            char[]   splitPipe      = { '|' };
            string[] slotValueArray = rawTextLine.Split(splitPipe);

            //assign arrays to individual variables for ease of use
            string location = slotValueArray[0];
            string name     = slotValueArray[1];
            double price    = double.Parse(slotValueArray[2]);
            string foodType = slotValueArray[3];

            //determine Food type and build corresponding item
            if (foodType == Food.Chip)
            {
                Chips holderChip = new Chips(location, name, price);
                SlotItem = holderChip;
            }
            else if (foodType == Food.Drink)
            {
                Beverage holderBeverage = new Beverage(location, name, price);
                SlotItem = holderBeverage;
            }
            else if (foodType == Food.Candy)
            {
                Candy holderCandy = new Candy(location, name, price);
                SlotItem = holderCandy;
            }
            else if (foodType == Food.Gum)
            {
                Gum holderGum = new Gum(location, name, price);
                SlotItem = holderGum;
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes new instance of VendingMachine.
        /// </summary>
        public VendingMachine()
        {
            this.Balance = 0.0M;

            using (StreamReader sr = new StreamReader("vendingmachine.csv"))
            {
                while (!sr.EndOfStream)
                {
                    // string array of all read in values
                    string[] items = sr.ReadLine().Split("|");

                    // create new item object with read in values (slot location, name, price, type)
                    // Item item = new Item(items[0], items[1], decimal.Parse(items[2]), items[3]);
                    if (items[3] == "Gum")
                    {
                        Item item = new Gum(items[0], items[1], decimal.Parse(items[2]), items[3]);
                        this.Stock[items[0]] = item;
                    }
                    else if (items[3] == "Drink")
                    {
                        Item item = new Drink(items[0], items[1], decimal.Parse(items[2]), items[3]);
                        this.Stock[items[0]] = item;
                    }
                    else if (items[3] == "Chip")
                    {
                        Item item = new Chip(items[0], items[1], decimal.Parse(items[2]), items[3]);
                        this.Stock[items[0]] = item;
                    }
                    else if (items[3] == "Candy")
                    {
                        Item item = new Candy(items[0], items[1], decimal.Parse(items[2]), items[3]);
                        this.Stock[items[0]] = item;
                    }
                }
            }
        }
Exemplo n.º 18
0
        //Uploads inventory file into Dictionary where key is the slot location
        public void GetInventoryMethod(string directoryPath, string fileToRead)
        {
            //directoryPath is the new inputFile
            Directory.SetCurrentDirectory(directoryPath);

            string wholeDocument = File.ReadAllText(fileToRead).Trim();

            string[] eachLineArray = wholeDocument.Split("\r\n");
            for (int i = 0; i < eachLineArray.Length; i++)
            {
                string   currentLine      = eachLineArray[i];
                string[] currentLineArray = currentLine.Split("|");
                Products product          = null;

                if (currentLineArray[3] == "Chip")
                {
                    product = new Chips(currentLineArray[1], Decimal.Parse(currentLineArray[2]), currentLineArray[3], currentLineArray[0], 5);
                }
                else if (currentLineArray[3] == "Candy")
                {
                    product = new Candy(currentLineArray[1], Decimal.Parse(currentLineArray[2]), currentLineArray[3], currentLineArray[0], 5);
                }

                else if (currentLineArray[3] == "Gum")
                {
                    product = new Gum(currentLineArray[1], Decimal.Parse(currentLineArray[2]), currentLineArray[3], currentLineArray[0], 5);
                }

                else if (currentLineArray[3] == "Drink")
                {
                    product = new Drink(currentLineArray[1], Decimal.Parse(currentLineArray[2]), currentLineArray[3], currentLineArray[0], 5);
                }

                inventory.Add(currentLineArray[0].ToString(), product);
            }
        }
Exemplo n.º 19
0
        public Dictionary <string, List <VendingItem> > StockNewVendingMachine(string filePath)
        {
            Dictionary <string, List <VendingItem> > initialStock = new Dictionary <string, List <VendingItem> >();

            if (!File.Exists(filePath))
            {
                throw new Exception("File path isn't valid.");
            }
            try
            {
                using (StreamReader sr = new StreamReader(filePath))
                {
                    while (!sr.EndOfStream)
                    {
                        string   line = sr.ReadLine();
                        string[] vendItemProperties = line.Split(delimiters);
                        if (vendItemProperties.Length != 3)
                        {
                            throw new Exception("A vending item is not formatted correctly: " + line);
                        }
                        // This assumes all input files will be coming in with the format(Location|Product_Name|Price)
                        string productLocation = vendItemProperties[SlotID];
                        string productName     = vendItemProperties[ProductName];
                        bool   validCost       = decimal.TryParse(vendItemProperties[Cost], out decimal productCost);
                        if (!validCost)
                        {
                            throw new Exception("The file had an invalid cost: " + line);
                        }

                        switch (productLocation[0])
                        {
                        case 'A':     // chips
                            Chip ch = new Chip(productCost, productName);
                            List <VendingItem> fiveOfChipCH = new List <VendingItem> {
                                ch, ch, ch, ch, ch
                            };
                            initialStock[productLocation] = fiveOfChipCH;
                            break;

                        case 'B':     //candy
                            Candy ca = new Candy(productCost, productName);
                            List <VendingItem> fiveOfCandyCA = new List <VendingItem> {
                                ca, ca, ca, ca, ca
                            };
                            initialStock[productLocation] = fiveOfCandyCA;
                            break;

                        case 'C':     // drinks
                            Drink dr = new Drink(productCost, productName);
                            List <VendingItem> fiveOfDrinkDR = new List <VendingItem> {
                                dr, dr, dr, dr, dr
                            };
                            initialStock[productLocation] = fiveOfDrinkDR;
                            break;

                        case 'D':     // gum
                            Gum g = new Gum(productCost, productName);
                            List <VendingItem> fiveOfGumG = new List <VendingItem> {
                                g, g, g, g, g
                            };
                            initialStock[productLocation] = fiveOfGumG;
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("StreamReader encountered a problem: " + e.Message);
            }

            return(initialStock);
        }
Exemplo n.º 20
0
        public VendingMachine(string file)
        {
            Inventory = new Dictionary <string, Product> {
            };

            // Sets up File to read in to the inventory from a txt file
            string directory         = Environment.CurrentDirectory;
            string inventoryFile     = file;
            string inventoryFullPath = Path.Combine(directory, inventoryFile);

            using (StreamReader sr = new StreamReader(inventoryFullPath))
            {
                while (!sr.EndOfStream)
                {
                    Product  prod         = null;
                    string   line         = sr.ReadLine();
                    string[] breaks       = line.Split("|");
                    string   slot         = breaks[0];
                    string   productName  = breaks[1];
                    string   productPrice = breaks[2];
                    string   productType  = breaks[3];
                    // Check to see if we get a vaild price of a product
                    if (!double.TryParse(productPrice, out double result))
                    {
                        //Log.AddTransactiontoLog($"{slot}: Bad Inventory Input: Price needs to be decimal", 0, this.Balance);
                        continue;
                    }
                    // Make sure we did not already have in item in that location
                    if (Inventory.ContainsKey(slot))
                    {
                        //Log.AddTransactiontoLog($"{slot}: Bad Inventory Input: This Slot is already filled with another product!", 0, this.Balance);
                        continue;
                    }
                    // Checks type and add the correct type to the inventory
                    if (productType.Contains("Chip"))
                    {
                        prod = new Chip(productName, double.Parse(productPrice));
                    }
                    else if (productType.Contains("Drink"))
                    {
                        prod = new Drink(productName, double.Parse(productPrice));
                    }
                    else if (productType.Contains("Gum"))
                    {
                        prod = new Gum(productName, double.Parse(productPrice));
                    }
                    else if (productType.Contains("Candy"))
                    {
                        prod = new Candy(productName, double.Parse(productPrice));
                    }
                    else
                    {
                        // We did not get a valid input so we report and move on
                        //Log.AddTransactiontoLog($"{slot}:Bad Inventory Input: No Product of this type exists.", 0, this.Balance);
                        continue;
                    }
                    Inventory.Add(slot, prod);
                }
                Report.SetupReportWithInventory(Inventory);
            }
        }