You are on page 1of 5

GR ENG SIS TELECOMUN / GR ENG TELEMÀTICA

PROJECTE DE PROGRAMACIÓ

Introduction to Object-Oriented Programming (II)


This document is the continuation of “Introduction to Object-Oriented Programming
(I)”. In your PC, go to the folder where you have the activity you did last week. Right-
click the “PracticaGuiadaPOO.sln” solution file to re-open the project in Visual Studio.

Objectives
At the end of this activity, you should be able to build classes and applications that use
other classes.

An object that has other objects


Next, we are going to build the class CList that manages a list of people. The class
CList has a vector of elements of class CPerson. The elements are stored in the
vector sequentially, starting from position 0. MAXP is a constant that marks the capacity
of vector, that is, the maximum number of people that can be stored in the list. We will
also need to store the information on how many people the list contains.

using System;
using System.Collections.Generic;
using System.Text;

namespace PeopleLib
{
public class CList
{
const int MAXP = 10; // maximum number of people
int number; // number of people in the list
CPerson[] people; // vector of people

/// Constructor. Initializes the attributes of the list


public CList()
{
number = 0;
people = new CPerson[MAXP];
}

/// Adds a person at the end of the list


/// param p: The person to be added
/// returns: 0 everything Ok, -1 the vector was full
public int AddPerson(CPerson p)
{
if (number == MAXP)
{
return -1;
}
else
{
people[number] = p;
number++;
return 0;
}
}
/// Returns the person in a particular position of the list
/// param i: Position in the list
/// returns: Person at "i", null if index not valid
public CPerson GetPerson(int i)
{
if (i < 0 || i >= number)
{
return null;
}
else
{
return people[i];
}
}
}

1. Add a new file with the definition of the class CList to your PeopleLib library.
To add the file, right-click the PeopleLib project in the Solution Explorer and pick
up the Add->New Item option. Select the Class template and name it CList.cs.
Copy the code of CList above. Do not forget the word “public” to make the
class accessible (“public class CList”).

Use this main program to check the new class (review points 1.6 to 1.9 of the of
“Introduction to Object-Oriented Programming (I)” guide if you do not
remember how to do this):

using PeopleLib;

namespace PeopleConsole
{
class Program
static void Main(string[] args)
{
// Create an empty list and three people
CList myList = new CList();
CPerson p1 = new CPerson(22, 165, "Ana");
CPerson p2 = new CPerson(19, 180, "Juan");
CPerson p3;

// Add two people to the list


myList.AddPerson(p1);
myList.AddPerson(p2);

// Get the first person in the list


p3 = myList.GetPerson(0);
if (p3 != null)
{
Console.WriteLine("The first person is " + p3.GetName());
}
else
{
Console.WriteLine("There is nobody in the list");
}
}
}
}

2
Notice the way of interacting with all objects (myList, p1, p2, and p3), always
through public methods in their respective classes.

2. Add the following methods to the definition of the class CList:


• public int GetNumber(): returns the number of people on the list.
• public CPerson GetYoungestPerson(): returns the youngest
person in the list, returns null if the list is empty.
Then, add the code to the main program to write a message on the screen
indicating how many people there are in the list and who is the youngest one.

Your solution should be similar to this (class and main respectively):

public int GetNumber()


{
return number;
}

public CPerson GetYoungestPerson()


{
if (number == 0)
{
return null;
}
else
{
CPerson youngest = people[0];
for (int i = 1; i < number; i++)
{
if (youngest.IsOlderThan(people[i]))
{
youngest = people[i];
}
}
return youngest;
}
}

// Get the number of people in the list


int n = myList.GetNumber();
Console.WriteLine("The are {0} people in the list ", n);

// Get the youngest person in the list


Person p4 = myList.GetYoungestPerson();
if (p4 != null)
{
Console.WriteLine("The youngest person is " + p4.GetName());
}
else
{
Console.WriteLine("There is nobody in the list");
}

3
In the previous solution, we have used the method IsOlderThan in the class
CPerson to compare the ages of youngest and people[i]. We could also
have accessed the age through the GetAge method:
...
if (youngest.GetAge() > people[i].GetAge())
{
youngest = people[i];
}
...

3. Complete the definition of the class CList with the following method:
• public int LoadFromFile(string filename): fills the list with
the contents of a text file. The text file contains one line per person, and for
each person the age, height, and name values separated by ‘:’. The method
receives the name of the file and returns an integer with the result of the
operation: 0 if the file has been successfully loaded, -1 if the file is not found,
or -2 if there is a format error.
Then, use any text editor to create a text file like this:
23:165:Ana
34:170:Juan
15:157:Alba
18:172:Oscar
24:180:Pedro
Save the text file to the bin\Debug folder of the console application. Finally, add
the code to the main program to load the file to an object of the class CList
and then write on the screen the names of all the people on the list. Run your
application to test your code.

Your solution should be similar to this (class and main respectively):

/// Fills the list with the contents of a text file


/// param filename: the name of the file
/// returns: 0 if everything ok
/// -1 if the file is not found
/// -2 if there is a format error
public int LoadFromFile(string filename)
{
StreamReader r = null;
try
{
r = new StreamReader(filename);
number = 0;
string line = r.ReadLine();
while (line != null && number < MAXP)
{
string[] words = line.Split(':');
if (words.Length != 3)
{
r.Close();
return -2;
}

4
int age = Convert.ToInt32(words[0]);
float height = Convert.ToSingle(words[1]);
string name = words[2];
CPerson p = new CPerson(age, height, name);
people[number] = p;
number++;
line = r.ReadLine();
}
return 0;
}
catch (FileNotFoundException)
{
return -1;
}
catch (FormatException)
{
r.Close();
return -2;
}
}

// Create a new list


CList nList = new CList();

// Fill the list with the contents of file "peoplelist.txt"


int e = nList.LoadFromFile("peoplelist.txt");
if (e == 0)
{
Console.WriteLine("File loaded");
}
else if (e == -1)
{
Console.WriteLine("File not found!");
}
else if (e == -2)
{
Console.WriteLine("Format error!");
}

// Write the names of all people in the list


for (int i = 0; i < nList.GetNumber(); i++)
{
CPerson p = nList.GetPerson(i);
Console.WriteLine(p.GetName());
}

Console.ReadKey();

Notice that we have to create a new person with the values from each line to add
it to the vector (CPerson p = new CPerson(age, height, name)).

You might also like