More Exercises: Objects and Classes - 2. Oldest Family Member
Здравейте, на More Exercises: Objects and Classes - 2. Oldest Family Member ми дава 60 точки.
Условието е това:
2. Oldest Family Member
Create two classes – Family and Person. The Person class should have Name and Age properties. The Family class
should have a list of people, a method for adding members (void AddMember(Person member)) and a method
returning the oldest family member (Person GetOldestMember()). Write a program that reads the names and
ages of N people and adds them to the family. Then print the name and age of the oldest member.
Examples
Input Output
3 Annie 5
Pesho 3
Gosho 4
Annie 5
Моят код
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public Person(){}
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
public string Name {get; set;}
public int Age {get; set;}
}
public class Family
{
public Family()
{
this.OrderPersons = new List<Person>();
}
public List<Person> OrderPersons {get; set;}
public void AddMember(Person member)
{
OrderPersons.Add(member);
}
public void GetOldestMember()
{
var currentPersona = new Person{Name = "one", Age = -1};
foreach(var kvp in OrderPersons)
{
if (currentPersona.Age < kvp.Age)
{
currentPersona = kvp;
}
} // end foreach
Console.WriteLine("{0} {1}", currentPersona.Name, currentPersona.Age);
}
} // end class Family
public class Program
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
var currentFamily = new Family();
for(int i = 0; i < n; i++)
{
string[] input = Console.ReadLine()
.Split();
var member = new Person(input[0], int.Parse(input[1]));
currentFamily.AddMember(member);
} // end for
if(currentFamily.OrderPersons.Count > 0)
{
currentFamily.GetOldestMember();
}
}
}
// 3
// Pesho 3
// Gosho 4
// Annie 5
// 5
// Steve 10
// Christopher 15
// Annie 4
// Ivan 35
// Maria 34