Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用户已经活了多少天_C#_Calculator - Fatal编程技术网

C# 用户已经活了多少天

C# 用户已经活了多少天,c#,calculator,C#,Calculator,我编写了一段代码,用来计算用户的生存时间。但问题是,如果用户不输入整数,例如一月或其他什么,程序就会陷入地狱。我需要知道如何阻止这一切 int inputYear, inputMonth, inputDay; Console.WriteLine("Please enter the year you were born: "); inputYear = int.Parse(Console.ReadLine()); Console.WriteLine("Please enter the Mont

我编写了一段代码,用来计算用户的生存时间。但问题是,如果用户不输入整数,例如一月或其他什么,程序就会陷入地狱。我需要知道如何阻止这一切

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();
如果用户未输入整数,例如一月或其他

那么你可以用这个方法

以指定样式转换数字的字符串表示形式 并将特定于区域性的格式转换为其等效的32位带符号整数。A. 返回值指示转换是否成功

而且
TryParse
方法不会抛出任何异常,这就是为什么不需要对其使用任何try-catch块


这远远超出我的水平,我不知道这里发生了什么

嗯。我试着解释得更深一些

你抱怨的是用户输入正确吗?正如你所说,你想把
int
作为输入。不是像“一月”或“五月”这样的字符串

当您使用方法读取输入时,它返回一个
字符串作为返回类型,而不是
int
。用户输入的
3
1月
与此无关,此方法将它们作为
字符串
返回,而不管它们的类型是什么


3
January
是本例中的字符串但是我们如何检查这些字符串是否可以转换为整数值?这就是为什么我们使用
Int32.TryParse
方法的部分原因。此方法检查这些输入是否可转换为整数,因此我们可以在
DateTime
构造函数中将此整数用作实整数。

这是因为您使用的是int.Parse(Console.ReadLine());-int代表整数。你可以在你的代码周围放一个try-catch块


原始代码将位于try块中,因为您希望尝试运行它-但是如果出现错误(例如,用户键入jan),catch块将处理错误,并且您的程序可以顺利运行。

Int32.TryParse(字符串,out-into)-在成功时返回布尔值。请始终精确说明您的程序“下地狱”的方式。到底发生了什么?虽然这个具体案例很简单,可以看出您可能遇到了未处理的异常,但在一般情况下,失败的确切方式可能并不明显。对不起,我是新手,不知道如何阅读此内容。if(Int32.TryParse(s,out month))做什么?@WindowsProdigy7你没读我的答案吗?它表示:将指定样式和区域性特定格式的数字的字符串表示形式转换为其等效的32位带符号整数。返回值指示转换是否成功。它检查您的输入是否可转换为
Int32
。如果对话成功,则返回
true
。如果您的对话不成功,它将返回
false
。是的,这看起来是一个很好的解决方案!无论如何,如果有用户交互,我会添加一个try-and-catch块——因为错误处理很重要!这真的节省了时间!这远远超出了我的水平,我不知道这里发生了什么,所以取字符串s,看看它是否可以转换成不带“除”的int。它通过Numberstyles.Integer查看它是否希望成为int,CultureInfo.InvariantCulture也不例外。那么我们这个月做什么呢?
Console.WriteLine("Please enter the Month you were born: ");
string s = Console.ReadLine();
int month;
if(Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out month))
{
   // Your string input is valid to convert integer.
   month = int.Parse(s);
}
else
{
   // Your string input is invalid to convert integer.
}