C#
public static int getAge(int yearOfBirth)
{
int CurrentYear = DateTime.Now.Year;
int age = CurrentYear - yearOfBirth;
return age;
}
In this function, I calculate age according to the birth year as an integer.
public static void distributionByAge()
{
int child = 0; //between 0-16
int youngAdults = 0; //between 17-30
int middleAged = 0; //between 30-55
int oldAged = 0; //above 55
var lines = File.ReadAllLines(@"data.csv"); // read file
foreach (var line in lines) // Reads file line by line
{
string[] values = line.Split(","); // Split each value
string birthYear = values[2]; // Birth year is value number 2 of each string/line
int age = getAge(Int32.Parse(birthYear));
// Check the age range
if (age>=0 || age<=16)
{
// If the age is between 0 and 16 increment count
child++;
}
else if (age>=17 || age<=30)
{
// If the age is between 17 and 30 increment count
youngAdults++;
}
else if (age>=31 || age<=55)
{
// If the age is between 31 and 55, increment count
middleAged++;
}
else
{
// If tge afe is above 55, increment count
oldAged++;
}
}
// Print results in percentages
int total = child + youngAdults + middleAged + oldAged;
Console.WriteLine("-------------------------------------------------------------------");
Console.WriteLine("Child: ");
Console.WriteLine(getPercentage(total, child) + "%");
Console.WriteLine("-------------------------------------------------------------------");
Console.WriteLine("Young Adults: ");
Console.WriteLine(getPercentage(total, youngAdults) + "%");
Console.WriteLine("-------------------------------------------------------------------");
Console.WriteLine("Middle-Aged Adults: ");
Console.WriteLine(getPercentage(total, middleAged) + "%");
Console.WriteLine("-------------------------------------------------------------------");
Console.WriteLine("Old-Aged Adults: ");
Console.WriteLine(getPercentage(total, oldAged) + "%");
}
These are my functions and I am trying to read the CSV file, take the year of birth information and calculate the ages according to it. I had to convert string type to int but I get unhandled exception and wrong type errors.