【发布时间】:2013-12-28 12:16:52
【问题描述】:
我编写了一段代码,用于计算用户存活的时间。但问题是,如果用户不输入整数,例如一月或其他东西,程序就会下地狱。我需要知道如何阻止这种情况。
int inputYear, inputMonth, inputDay;
Console.WriteLine("Please enter the year you were born: ");
inputYear = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the Month you were born: ");
inputMonth = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the day you were born: ");
inputDay = int.Parse(Console.ReadLine());
DateTime myBrithdate = new DateTime(inputYear,inputMonth, inputDay);
TimeSpan myAge = DateTime.Now.Subtract(myBrithdate);
Console.WriteLine(myAge.TotalDays);
Console.ReadLine();
【问题讨论】:
-
Int32.TryParse(string, out into) - 成功返回布尔值
-
请务必准确如何您的程序“下地狱”。究竟会发生什么?虽然这种特定情况很简单,可以看出您可能遇到了未处理的异常,但在一般情况下,失败的确切方式可能并不明显。
标签: c# calculator