For my project, I am required to validate the file input based on specific criteria, and then sort and display results. Guidelines below.
The file containing the results of the census is structured as follows:
Field: Age Valid Values: Numeric greater than 0
Field: Gender Valid Values: M, m, F, f
Field: Marital Status Valid Values: M, m, S, s
Field: District Valid Values: Numeric 1 – 22
The fields in each record will be separated by a comma. For example: 21, M, S, 1
The city has 22 districts. The census department wants to see a listing of how many residents are in each district, and a count of residents in each of the following age groups (for all the districts combined): under 18, 18 through 30, 31 through 45, 46 through 64, and 65 or older.
I am currently just looking to get by District Results running correctly. However when I input the following file the results are 10 time more than they should.
File Input:
27, m, f, 4
8, m, f, 2
63, m, f, 4
31, m, f, 3
44, m, f, 3
39, m, f, 4
20, m, f, 1
17, m, f, 1
79, m, f, 1
84, m, f, 4
I think I’ve identified the for loop causing the issue(see comment), but I’m unsure of why or how to fix. Thank you.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Agron__Jared_PROJECT_2 { class Program { const int CENSUS_SIZE = 10; static void Main(string[] args) { //create file stream and stream reader FileStream fStream = new FileStream("censusData.txt", FileMode.Open, FileAccess.Read); StreamReader inFile = new StreamReader(fStream); //Variables int a = 0; int d = 0; string inputRecord = ""; int[] districtCount = new int[4]; int[] ageData = new int[CENSUS_SIZE]; int[] districtData = new int[CENSUS_SIZE]; inputRecord = inFile.ReadLine(); //read first line while (inputRecord != null) { string[] fields = inputRecord.Split(','); if (int.TryParse(fields[0], out a) && a >= 0 && int.TryParse(fields[3], out d) && d <= 22 && d > 0 ) { processRecord(fields, ageData, districtData, districtCount); } else { Console.WriteLine("File error."); }//end if inputRecord = inFile.ReadLine(); }//end while printDistrict(districtCount); }//end main static void processRecord(string[] fields, int[] ageData, int[] districtData, int[] districtCount) { //I THINK ITS THIS FOR LOOP causing issues because when I //change the 'i <' part of the loop my answer changes for (int i = 0; i < CENSUS_SIZE; i++) { getData(fields, ageData, districtData, i); sortDistrict(districtData, districtCount, i); }//end for } static void getData(string[] fields, int[] ageData, int[] districtData, int i) { ageData[i] = int.Parse(fields[0]); districtData[i] = int.Parse(fields[3]); } static void sortDistrict(int[] districtData, int[] districtCount, int i) { districtCount[districtData[i] - 1]++; } static void printDistrict(int[] districtCount) { for(int i = 1; i < (districtCount.Length+1); i++) { Console.WriteLine("District {0} = {1}", i, districtCount[i - 1]); } } } }