0

При вызове метода Input возникает ошибка "Ссылка на объект не указывает на экземпляр объекта", которая ссылается на массив. Код и скрин с ошибкой приведен ниже.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarAndBus
{
    class tCar
    {
        public double x { get; set; }
        public double y { get; set; }
        public double r { get; set; }
        public tCar(double x, double y)
        {
            this.x = x;
            this.y = y;
            //Output();
        }
        public virtual void Move(double ed, double a)
        {
            this.r = a * Math.PI / 180;
            this.x = this.x + ed * Math.Cos(r);
            this.y = this.y + ed * Math.Sin(r);
            Output();
        }
        public virtual void Output()
        {
            Console.WriteLine($"x= {this.x,2:f2} y= {this.y,2:f2}");
        }
    }
    class tBus : tCar
    {
        public string[] passengers { get; set; }
        public double money { get; set; }
        public double moneyPassengers { get; set; }
        public int capacity { get; set; }
        public tBus(double x, double y, int capacity) : base(x,y)
        {
            this.money = 0;
            this.capacity = capacity;
            string[] passengers = { };
        }
        public override void Move(double ed, double a)
        {
            this.r = a * Math.PI / 180;
            this.x = this.x + ed * Math.Cos(r);
            this.y = this.y + ed * Math.Sin(r);

            for (int i=0; i<this.passengers.Length; i++)
            {
                switch (this.passengers[i])
                {
                    case "обычный":
                        this.money+= 2*ed;
                        break;
                    case "студент":
                        this.money= 1.25*ed;
                        break;
                }

            }
            this.Output();

        }
        public override void Output()
        {
            Console.WriteLine($"x= {this.x,2:f2} y= {this.y,2:f2}\nКол-во пассажиров: {this.passengers.Length}\nКол-во полученных денег: {this.money,6:f2}\nВместимость автобуса: {this.capacity}");
        }
        public void Input(int people)
        {
            if (this.passengers.Length + people <= this.capacity)
            {
                for (int i = 0; i < people; i++)
                {
                    Console.Write($"Выберите тип {i + 1}-го вошедшего пассажира: 1-обычный 2-студент ");
                    int type = Convert.ToInt32(Console.ReadLine());
                    int countOfArr = this.passengers.Length;
                    switch (type)
                    {
                        case 1:
                            this.passengers[countOfArr] = "обычный";
                            break;
                        case 2:
                            this.passengers[countOfArr] = "студент";
                            break;
                    }
                }
                this.Output();
            }
            else
            {
                Console.Write("Недостаточно мест в автобусе");
            }
        }

        public void Exit(int passengers)
        {

            if (this.passengers.Length - passengers > 0)
            {
                for (int i = 0; i < passengers; i++)
                {
                    int []indexes = { this.passengers.Length - i };
                    this.passengers = (from x in this.passengers where !(from y in indexes select this.passengers.ElementAt(y)).Contains(x) select x).ToArray();
                }
                this.Output();
            }else
            {
                Console.Write("Количество человек в автобусе меньше, чем то значение, которое вы передаете в параметре");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            tBus Bus = new tBus(0, 0, 50);
            Bus.Input(2);
            Bus.Move(20, 45);
            Bus.Exit(3);
            Bus.Exit(1);
            Bus.Move(20, 135);
            Bus.Move(20, 225);
            Bus.Move(20, 315);
            Console.ReadKey();
        }
    }
}

введите сюда описание изображения

corocoto
  • 192

1 Answers1

1

В конструкторе вместо инициализации поля passengers происходит инициализация локальной переменной.

Поле же остается null, поэтому при попытке получить у него Length и происходит указанная ошибка.

Grundy
  • 81,538