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



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,但我遇到了未处理的异常和错误的类型错误。

从错误消息中可以清楚地看到,在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

最新更新