Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

AnastasiyaG avatar AnastasiyaG 4 Точки

04. Orders//Associative Arrays//Objects and classes

Здравейте, Тази задача казаха, че може да се реши с класове и обекти. МОже ли някой да даде примерно решение?

 

_______________________

4.Orders

Write a program that keeps information about products and their prices. Each product has a name, a price and a quantity. If the product doesn’t exist yet, add it with its starting quantity.

If you receive a product, which already exists, increase its quantity by the input quantity and if its price is different, replace the price as well.

You will receive products’ names, prices and quantities on new lines. Until you receive the command "buy", keep adding items. When you do receive the command "buy", print the items with their names and total price of all the products with that name.

Input

  • Until you receive "buy", the products will be coming in the format: "{name} {price} {quantity}".
  • The product data is always delimited by a single space.

Output

  • Print information about each product in the following format:
    "{productName} -> {totalPrice}"
  • Format the average grade to the 2nd digit after the decimal separator.

 

Examples

Input

Output

Beer 2.20 100

IceTea 1.50 50

NukaCola 3.30 80

Water 1.00 500

Buy

Beer -> 220.00

IceTea -> 75.00

NukaCola -> 264.00

Water -> 500.00

Beer 2.40 350

Water 1.25 200

IceTea 5.20 100

Beer 1.20 200

IceTea 0.50 120

Buy

Beer -> 660.00

Water -> 250.00

IceTea -> 110.00

CesarSalad 10.20 25

SuperEnergy 0.80 400

Beer 1.35 350

IceCream 1.50 25

buy

CesarSalad -> 255.00

SuperEnergy -> 320.00

Beer -> 472.50

IceCream -> 37.50

 

Тагове:
0
Fundamentals Module
nickwork avatar nickwork 657 Точки

Привет - написах ти набързо едно решение с класове :)

 

using System;
using System.Collections.Generic;
using System.Linq;

namespace Temp
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Product> products = new List<Product>();

            while (true)
            {
                string input = Console.ReadLine();

                if (input.ToLower().Equals("buy"))
                {
                    break;
                }

                string[] inputInfo = input.Split();

                string productType = inputInfo[0];
                decimal price = decimal.Parse(inputInfo[1]);
                decimal quantity = decimal.Parse(inputInfo[2]);
                
                if (!products.Any(x => x.Name == productType))
                {
                    products.Add(new Product(productType, price, quantity));
                }
                else
                {
                    Product currentProduct = products.FirstOrDefault(x => x.Name == productType);

                    currentProduct.Quantity += quantity;
                    currentProduct.Price = price;
                }
            }

            foreach (var product in products)
            {
                Console.WriteLine($"{product.Name} -> {product.GetTotalPrice():f2}");
            }
        }
    }

    public class Product
    {
        public Product(string name, decimal price, decimal quantity)
        {
            this.Name = name;
            this.Price = price;
            this.Quantity = quantity;
        }

        public string Name { get; set; }

        public decimal Price { get; set; }

        public decimal Quantity { get; set; }


        public decimal GetTotalPrice()
        {
            return this.Price * this.Quantity;
        }
    }
}

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.