Professional Documents
Culture Documents
PROJECTE DE PROGRAMACIÓ
Objectives
At the end of this activity, you should be able to build classes and applications that use
other classes.
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
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;
2
Notice the way of interacting with all objects (myList, p1, p2, and p3), always
through public methods in their respective classes.
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.
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;
}
}
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)).