Професионална програма
Loading...
+ Нов въпрос
v.angelov92 avatar v.angelov92 6 Точки

08. Vehicle Catalogue

Здравейте, при решаването на задача 08.Vehicle Catalogue Objects and Classes - Lab, достигнах само до верни първи и втори нулеви теста. Отговорите съвпадат с дадени примери, но точките са си 0/100 в Джъдж. С малкото си знания не успявам да намеря грешката в кода си. Ще се радвам, някой с повече знания да погледне кога и да даде ако не верния отговор, поне съвет как да се справя със задачата. Благодаря.

Условие на задачата:

1.   Vehicle Catalogue

Your task is to create a Vehicle catalogue, which contains only Trucks and Cars.

Define a class Truck with the following properties: Brand, Model and Weight.

Define a class Car with the following properties: Brand, Model and Horse Power.

Define a class Catalog with the following properties: Collections of Trucks and Cars.

You must read the input until you receive the "end" command. It will be in following format: {type}/{brand}/{model}/{horse power / weight}

In the end you have to print all of the vehicles ordered alphabetical by brand, in the following format:

Cars:

{Brand}: {Model} - {Horse Power}hp

Trucks:

{Brand}: {Model} - {Weight}kg

Examples

Input

Output

Car/Audi/A3/110

Car/Maserati/Levante/350

Truck/Mercedes/Actros/9019

Car/Porsche/Panamera/375

end

Cars:

Audi: A3 - 110hp

Maserati: Levante - 350hp

Porsche: Panamera - 375hp

Trucks:

Mercedes: Actros - 9019kg

Car/Subaru/Impreza/152

Car/Peugeot/307/109

end

Cars:

Peugeot: 307 - 109hp

Subaru: Impreza - 152hp

Hints

This is how your class Catalog should look like.

08. Vehicle Catalogue

Don’t forget to create instances for the two Lists.

You can do it in the constructor of CatalogueVehicle.

Код на задачата:

https://pastebin.com/UUVv54i0

 

1
Fundamentals Module
MartinBG avatar MartinBG 3827 Точки
Best Answer

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

 

Правилно сте създали класовете Car и Truck, както и CatalogueVehicle, но се пропуснали да инициализирате двете му пропъртита:

 

    class CatalogueVehicle
    {
        public List<Car> Cars { get; }
        public List<Truck> Trucks { get; }

        public CatalogueVehicle() // инициализация на Cars и Trucks листовете в конструктора
        {
            Cars = new List<Car>();
            Trucks = new List<Truck>();
        }
    }

 

 

Имате грешки в логиката на програмата, затова ще мина накратко през основните стъпки:

1. Създаваме си инстанция на CatalogueVehicle, в която ще съхраняваме колите и камионите:

CatalogueVehicle catalogueVehicle = new CatalogueVehicle();

2. Четем входите данни до "end" и според вида им създаваме инстанция на Car или Truck и ги добавяме в съответния лист на catalogueVehicle:

                if (typeOfVehicle == "Car")
                {
                    catalogueVehicle.Cars.Add(new Car
                    {
                        Brand = brandOfVehicle,
                        Model = modelOfVehicle,
                        HorsePower = horseOrWeight
                    });
                } else if (typeOfVehicle == "Truck")
                {
                    catalogueVehicle.Trucks.Add(new Truck()
                    {
                        Brand = brandOfVehicle,
                        Model = modelOfVehicle,
                        Weight = horseOrWeight
                    });
                }

3. Отпечатваме резултата, като сортираме колите и камионите по марка

 

Цялата програма:

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

namespace Campain
{
    internal static class Program
    {
        static void Main(string[] args)
        {
            CatalogueVehicle catalogueVehicle = new CatalogueVehicle();

            while (true)
            {
                string[] input = Console.ReadLine().Split("/");

                if (input[0] == "end")
                {
                    break;
                }

                string typeOfVehicle = input[0];
                string brandOfVehicle = input[1];
                string modelOfVehicle = input[2];
                int horseOrWeight = int.Parse(input[3]);

                if (typeOfVehicle == "Car")
                {
                    catalogueVehicle.Cars.Add(new Car
                    {
                        Brand = brandOfVehicle,
                        Model = modelOfVehicle,
                        HorsePower = horseOrWeight
                    });
                } else if (typeOfVehicle == "Truck")
                {
                    catalogueVehicle.Trucks.Add(new Truck()
                    {
                        Brand = brandOfVehicle,
                        Model = modelOfVehicle,
                        Weight = horseOrWeight
                    });
                }
            }

            if (catalogueVehicle.Cars.Count > 0)
            {
                Console.WriteLine($"Cars:");
                foreach (Car carList in catalogueVehicle.Cars.OrderBy(car => car.Brand))
                {
                    Console.WriteLine($"{carList.Brand}: {carList.Model} - {carList.HorsePower}hp");
                }
            }

            if (catalogueVehicle.Trucks.Count > 0)
            {
                Console.WriteLine($"Trucks:");
                foreach (Truck truckList in catalogueVehicle.Trucks.OrderBy(truck => truck.Brand))
                {
                    Console.WriteLine($"{truckList.Brand}: {truckList.Model} - {truckList.Weight}kg");
                }
            }
        }
    }

    class Car
    {
        public string Brand { get; set; }
        public string Model { get; set; }
        public int HorsePower { get; set; }
    }

    class Truck
    {
        public string Brand { get; set; }
        public string Model { get; set; }
        public int Weight { get; set; }
    }

    class CatalogueVehicle
    {
        public List<Car> Cars { get; }
        public List<Truck> Trucks { get; }

        public CatalogueVehicle()
        {
            Cars = new List<Car>();
            Trucks = new List<Truck>();
        }
    }
}

 

1
v.angelov92 avatar v.angelov92 6 Точки

Да, определено има разлика между моя и вашия код. Много благодаря за разяснението и за отделеното време. Поздрави.

2
koknq avatar koknq 18 Точки

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

namespace ConsoleApp14
{
    class Catalog
    {
        public List<Car> Cars { get; set; }
        public List<Truck> Trucks { get; set; }
        public Catalog()
        {
            Cars = new List<Car>();
            Trucks = new List<Truck>();
        }
    }
    class Truck
    {
        public string Brand { get; set; }
        public string Model { get; set; }
        public int Weight { get; set; }
    }
    class Car
    {
        public string Brand { get; set; }
        public string Model { get; set; }
        public int HorsePower { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Catalog catalog = new Catalog();
            
            while(true)
            {
                string command = Console.ReadLine();
                
                if(command == "end")
                {
                    break;
                }
                string[] command2 = command.Split('/');

                string type = command2[0];
                string brand = command2[1];
                string model = command2[2];
                int index = int.Parse(command2[3]);

                if (type == "Car")
                {
                    Car car = new Car();
                    car.Brand = brand;
                    car.Model = model;
                    car.HorsePower = index;
                    catalog.Cars.Add(car);

                }
                else if (type == "Truck")
                {
                    Truck truck = new Truck();
                    truck.Brand = brand;
                    truck.Model = model;
                    truck.Weight = index;
                    catalog.Trucks.Add(truck);
                }
                
            }

            if (catalog.Cars.Count > 0)
            {
                Console.WriteLine($"Cars:");
                foreach (Car car in catalog.Cars.OrderBy(car => car.Brand))
                {
                    
                    Console.WriteLine($"{car.Brand}: {car.Model} - {car.HorsePower}hp");
                }
            }
            if (catalog.Trucks.Count > 0)
            {
                Console.WriteLine($"Trucks:");
                foreach (Truck truck in catalog.Trucks.OrderBy(truck => truck.Brand))
                {
                    
                    Console.WriteLine($"{truck.Brand}: {truck.Model} - {truck.Weight}kg");
                }
            }
        }
    }
}

0