Loading...
StefanBuchvarov avatar StefanBuchvarov 0 Точки

Проблем със Controller класа от C# OOP Exam - 16 August 2020

При подаване на командата "AddComputer Laptop 4 Asus ROG 700" ми изписва:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at OnlineShop.Core.CommandInterpreter.AddComputer(String[] data, IController controller) in d:\Downloads\01. Structure_Skeleton\OnlineShop-Skeleton\OnlineShop\Core\CommandInterpreter.cs:line 132
   at OnlineShop.Core.CommandInterpreter.ExecuteCommand(String[] data, IController controller) in d:\Downloads\01. Structure_Skeleton\OnlineShop-Skeleton\OnlineShop\Core\CommandInterpreter.cs:line 25
   at OnlineShop.Core.Engine.Run() in d:\Downloads\01. Structure_Skeleton\OnlineShop-Skeleton\OnlineShop\Core\Engine.cs:line 32
   at OnlineShop.StartUp.Main() in d:\Downloads\01. Structure_Skeleton\OnlineShop-Skeleton\OnlineShop\StartUp.cs:line 24

Моля за помощ! Благодаря предварително!

Ако не нуждаете от допълнително код, моля кажете.

Кода на Controller класа ми е:

using OnlineShop.Common.Constants;
using OnlineShop.Models.Products;
using OnlineShop.Models.Products.Components;
using OnlineShop.Models.Products.Computers;
using OnlineShop.Models.Products.Peripherals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace OnlineShop.Core
{
    public class Controller : IController
    {
        public Controller()
        {
            computers = new List<Computer>();
            components = new List<Component>();
            peripherals = new List<Peripheral>();
        }
        public IReadOnlyCollection<IComputer> Computers => computers;
        private readonly List<Computer> computers;
        private readonly List<Component> components;
        private readonly List<Peripheral> peripherals;

        public string AddComponent(int computerId, int id, string componentType, string manufacturer, string model, decimal price, double overallPerformance, int generation)
        {
            Component comp =  null;
            switch (componentType)
            {
                case "CentralProcessingUnit":
                    comp = new CentralProcessingUnit(id, manufacturer, model, price, overallPerformance, generation);
                    break;
                case "Motherboard":
                    comp = new Motherboard(id, manufacturer, model, price, overallPerformance, generation);
                    break;
                case "PowerSupply":
                    comp = new PowerSupply(id, manufacturer, model, price, overallPerformance, generation);
                    break;
                case "RandomAccessMemory":
                    comp = new RandomAccessMemory(id, manufacturer, model, price, overallPerformance, generation);
                    break;
                case "SolidStateDrive":
                    comp = new SolidStateDrive(id, manufacturer, model, price, overallPerformance, generation);
                    break;
                case "VideoCard":
                    comp = new VideoCard(id, manufacturer, model, price, overallPerformance, generation);
                    break;
                default: throw new ArgumentException(ExceptionMessages.InvalidComponentType);
            }
            foreach (var item in components)
            {
                if (item.Id == id)
                {
                    throw new ArgumentException(ExceptionMessages.ExistingComponentId);
                }
            }
            computers.FirstOrDefault(x => x.Id == computerId).AddComponent(comp);
            components.Add(comp);
            return string.Format(SuccessMessages.AddedComponent, componentType, id, computerId);
        }

        public string AddComputer(string computerType, int id, string manufacturer, string model, decimal price)
        {
            Computer comp;
            switch (computerType)
            {
                case "DesktopComputer":
                    comp = new DesktopComputer(id, manufacturer, model, price);
                    break;
                case "Laptop":
                    comp = new Laptop(id, manufacturer, model, price);
                    break;

                default: throw new ArgumentException(ExceptionMessages.InvalidComputerType);
                    

            }
            foreach (var item in computers)
            {
                if (item.Id == comp.Id)
                {
                    throw new ArgumentException(ExceptionMessages.ExistingComputerId);
                }
            }
            computers.Add(comp);
            return String.Format(SuccessMessages.AddedComputer, id);
        }

        public string AddPeripheral(int computerId, int id, string peripheralType, string manufacturer, string model, decimal price, double overallPerformance, string connectionType)
        {
            Peripheral peri;
            switch (peripheralType)
            {
                case "Headset":
                    peri = new Headset(id, manufacturer, model, price, overallPerformance, connectionType);
                    break;
                case "Keyboard":
                    peri = new Keyboard(id, manufacturer, model, price, overallPerformance, connectionType);
                    break;
                case "Monitor":
                    peri = new Monitor(id, manufacturer, model, price, overallPerformance, connectionType);
                    break;
                case "Mouse":
                    peri = new Mouse(id, manufacturer, model, price, overallPerformance, connectionType);
                    break;

                default: throw new ArgumentException(ExceptionMessages.InvalidPeripheralType);
                    
            }
            foreach (var item in peripherals)
            {
                if (item.Id == id)
                {
                    throw new ArgumentException(ExceptionMessages.ExistingPeripheralId);
                }
            }
            computers.FirstOrDefault(x => x.Id == computerId).AddPeripheral(peri);
            peripherals.Add(peri);
            return String.Format(SuccessMessages.AddedPeripheral, peripheralType, id, computerId);

        }

        public string BuyBest(decimal budget)
        {
            double maxPerformance = components.Max(t => t.OverallPerformance);
            Computer comp = computers.FirstOrDefault(x => x.OverallPerformance == maxPerformance);
            if (comp == null || budget < comp.Price)
            {
                throw new ArgumentException(string.Format(ExceptionMessages.CanNotBuyComputer, budget));
            }
            computers.Remove(comp);
            return comp.ToString();
        }

        public string BuyComputer(int id)
        {
            Computer comp = computers.FirstOrDefault(x => x.Id == id);

            if (comp == null )
            {
                throw new ArgumentException(ExceptionMessages.NotExistingComputerId);
            }
            computers.Remove(comp);
            return comp.ToString();
        }

        public string GetComputerData(int id)
        {
            Computer comp = computers.FirstOrDefault(x => x.Id == id);

            if (comp == null)
            {
                throw new ArgumentException(ExceptionMessages.NotExistingComputerId);
            }
            
            return comp.ToString();
        }

        public string RemoveComponent(string componentType, int computerId)
        {
            Component comp = components.FirstOrDefault(x => x.GetType().Name == componentType);

            components.Remove(comp);

            foreach (var item in computers)
            {
                if (item.Id == computerId)
                {
                    item.RemoveComponent(componentType);
                }
            }
            return string.Format(SuccessMessages.RemovedComponent, componentType, comp.Id);
        }

        public string RemovePeripheral(string peripheralType, int computerId)
        {
            Peripheral peri = peripherals.FirstOrDefault(x => x.GetType().Name == peripheralType);

            peripherals.Remove(peri);

            foreach (var item in computers)
            {
                if (item.Id == computerId)
                {
                    item.RemovePeripheral(peripheralType);
                }
            }
            return string.Format(SuccessMessages.RemovedPeripheral, peripheralType, peri.Id);
        }
    }
}
 

Тагове:
0
Module: C# Advanced
nickwork avatar nickwork 657 Точки
Best Answer

Тук сякаш изглежда да е добре този метод, грешката е ,че нямаш инициализирана някъде (колекция, лист)..по добре пусни зип на цялата задача https://easyupload.io/, че по грешките виждам че гърми в различни класове

0
StefanBuchvarov avatar StefanBuchvarov 0 Точки

Заповядайте и благодаря Ви за помощта!

https://easyupload.io/ydd1qy

0
nickwork avatar nickwork 657 Точки

Пуснал си само 1 единствен файл, зипни цялата папка с всички класове и я ъплоудни 

0
StefanBuchvarov avatar StefanBuchvarov 0 Точки

https://easyupload.io/hbsi28

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