首页 > 解决方案 > adding values to an array in a method every time you call the method

问题描述

I have an array called passengers, lets say it has 10 places. I also have a class for new passenger which gonna have the age of the passenger. I want to add a new passenger to the array by his age. This passenger is gonna be created by its class through calling the constructor. Lets say I add only ONE passenger by calling the method and 9 places are EMPTY. The NEXT time a call the method, I want to add a new passenger in the next place in the passengers array! So every time I want to add a new passenger, i call the passenger method, and it will be saved in the next empty place in array, until it is full. A message will say it is full and no passenger can go on.

My problem with my code is that i have to enter all passengers at once! but i want to enter only one passenger every time I call the method.

public void Add_Passengers ()
    {
        Console.WriteLine("How old are the passengers?");

        for (int i = 0; i < passengers.Length; i++)
        {
            int age = Int32.Parse(Console.ReadLine());
            passengers[i] = new Passenger(age);
        }
    }

标签: c#

解决方案


    /// <summary>
    /// Passengers array
    /// </summary>
    public Passenger[] Passengers = new Passenger[10];

    public class Passenger
    {
        public int Age { get; set; }

        public Passenger(int age)
        {
            Age = age;
        }
    }

    public void AddPassenger()
    {
        // Get the number of passengers
        int passengerCount = Passengers.Count(p => p != null);

        if (passengerCount == Passengers.Length)
            Console.WriteLine("Maximum number of passengers");
        else
        {
            Console.WriteLine("How old are the passengers?");
            int age = int.Parse(Console.ReadLine());

            // Add passenger
            Passengers[passengerCount] = new Passenger(age);
        }
    }

推荐阅读