-1

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.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • 1
    [Debug your code!](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2022). `if (age>=0 || age<=16)` will always match. Use `if (age>=0 && age<=16)` instead. – Olivier Jacot-Descombes Nov 20 '22 at 15:15
  • 1
    Could you please show exceptions and errors? Could you add an extract (two or three lines) of data.csv? Anyway... if "Birth year is value number 2" then it should be `string birthYear = values[1];` – Salvatore Giuffrida Nov 20 '22 at 15:36
  • I suspect there's a non-integer value somewhere in `birthYear`. I would recommend first checking the input file for any errors, for example using CSV Lint plug-in for Notepad++ to technically validate the data https://github.com/BdR76/CSVLint and then either fix the data file, or send it back to whoever provided the data and ask them to fix it. – BdR Nov 20 '22 at 22:12

1 Answers1

0

It's pretty clear from the error message that somewhere in your data.csv there's a row where the second value is either missing or can't be parsed as an int.

It might be something like 22a or 2.0 or even banana. The way to correctly handle such things are to use TryParse instead of Parse, and when TryParse return false, you should decide what you want to do with the data in that row. Personally, I would probably just write it to console and ignore it later on in the program.

something like this:

// instead of int age = getAge(Int32.Parse(birthYear));
if(!int.TryParse(birthYear, out var year))
{
    Console.WriteLine("{0} is not a valid birth year", birthYear);
    continue;
}
var age = getAge(year);
// rest of your foreach loop here
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • I would throw an exception and just let the code crash, but do make sure to output the line number of the datafile in the exception message. Then I would just return the data file to whoever compiled it, and ask them to fix the birthyear column. I think in the long run, that's a better approach than trying to fix bad data in code and then let it continue with probably incorrect data. – BdR Nov 20 '22 at 22:05
  • @BdR Where did I suggest to try and fix the bad data? As a rule of thumb, when working with data you can't control there's always a chance that the data will be corrupt. Your code should anticipate things like that and crushing the entire program over one line of ill formatted data seems like a bad choice to me. IMO, Exceptions should be thrown under exceptional circumstances, and corrupt data is anything but exceptional. – Zohar Peled Nov 21 '22 at 06:50