csv 输入字符串格式不正确错误

ivqmmu1c  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(374)

C#语言

public static int getAge(int yearOfBirth) 
{
    int CurrentYear = DateTime.Now.Year;
    int age = CurrentYear - yearOfBirth;
    return age;
}

在这个函数中,我根据出生年份作为整数来计算年龄。

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) + "%");
}

这些是我的函数,我试图读取CSV文件,获取出生年份信息,并根据它计算年龄。我必须将字符串类型转换为int,但我得到了未处理的异常和错误类型的错误。

zqry0prt

zqry0prt1#

从错误消息中可以很清楚地看到,在data.csv的某个地方,有一行的第二个值要么丢失了,要么不能解析为int。
它可能是22a2.0,甚至是banana。正确处理这些问题的方法是使用TryParse而不是Parse,当TryParse返回false时,您应该决定如何处理该行中的数据。就我个人而言,我可能只是将其写入控制台,并在程序中忽略它。
就像这样:

// 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

相关问题