c# - 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);
}
}
解决方案
/// <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);
}
}
推荐阅读
- ios - 在 IOS 上运行 react-native 应用程序的一些麻烦
- android - 高程产生的阴影以圆形可绘制为背景但不以矩形显示
- ruby-on-rails - Heroku 上的 Bundler 无法运行正确的版本
- java - 如何识别收到消息的 MQTT 主题?
- sh - 使 sh 脚本启动多个 Tmux 会话
- selenium-webdriver - 将鼠标悬停在页脚上时如何获得下划线和 facebook 图标颜色
- c# - 将容器注册类型与 Shell 窗口标题链接
- algorithm - 我可以计算距离严格小于 delta 的最近分割点对吗
- javascript - 如何使电子浏览器全屏尺寸?
- c++ - 使用 GDB 调试时如何在特定地址打印 VTable 的虚拟功能