The program takes census data from a text file in the format age, gender, marital status, district. It then gives a list of residents by district (there are 22) and by 5 age groups. Any suggestions for improvement?
The only topics we have covered so far in class are methods, decisions, looping, and arrays.
static void Main(string[] args)
{
FileStream fStream = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(fStream);
string inputRecord = "";
string[] fields;
int[] ageData = new int[1000];
string[] genderData = new string[1000];
string[] maritalData = new string[1000];
int[] districtData = new int[1000];
int[] countDist = new int[23];
int[] ageGroup = new int[5];
inputRecord = inFile.ReadLine();
int i = 0;
while (inputRecord != null)
{
fields = inputRecord.Split(',');
ageData[i] = int.Parse(fields[0]);
genderData[i] = fields[1];
maritalData[i] = fields[2];
districtData[i] = int.Parse(fields[3]);
if (ageData[i] > 0 && ageData[i] <= 18)
{
ageGroup[0] = ageGroup[0] + 1;
}
if (ageData[i] > 18 && ageData[i] <= 30)
{
ageGroup[1] = ageGroup[1] + 1;
}
if (ageData[i] > 30 && ageData[i] <= 45)
{
ageGroup[2] = ageGroup[2] + 1;
}
if (ageData[i] > 45 && ageData[i] <= 64)
{
ageGroup[3] = ageGroup[3] + 1;
}
if (ageData[i] >= 65)
{
ageGroup[4] = ageGroup[4] + 1;
}
i++;
inputRecord = inFile.ReadLine();
}
Console.WriteLine("This Program takes census data from a file and lists residents by age group and district");
Console.WriteLine("Please ensure the file is formatted correctly! age,gender (M/F),marital status (M/S), and district");
for (int x = 1; x <= 22; x++)
for (int y = 0; y < districtData.Length; y++)
if (districtData[y] == x)
countDist[x]++;
for (int x = 1; x <= 22; x++)
Console.WriteLine("District " + x + " has " + countDist[x] + " citizens");
Console.WriteLine("------Amount of Residents per Age Group--------");
Console.WriteLine("Age Group 18 & under = {0}", ageGroup[0]);
Console.WriteLine("Age Group 18-30 = {0}", ageGroup[1]);
Console.WriteLine("Age Group 31-45 = {0}", ageGroup[2]);
Console.WriteLine("Age Group 46-64 = {0}", ageGroup[3]);
Console.WriteLine("Age Group 65 & over = {0}", ageGroup[4]);
}
EDIT
Per comments below, the instructor thinks I should get rid of the ageGroup and districtData. This is what he was suggesting I do - however, I have no idea how I'm going to change my logic that was using districtData.
for (int districtCount = 1; districtCount <= 22; districtCount++)
{
for (int districtNumber = 0; districtNumber < districtData.Length; districtNumber++)
{
if (districtData[districtNumber] == districtCount)
{
countDist[districtCount]++;
}
}
}