【问题标题】:How many days user has been alive calculator用户存活了多少天计算器
【发布时间】: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


【解决方案1】:

如果用户没有输入整数,例如一月或其他内容

然后你可以使用Int32.TryParse 方法..

以指定样式转换数字的字符串表示形式 和文化特定格式到其 32 位有符号整数等价物。一个 返回值表示转换是否成功。

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.
}

另外,TryParse 方法不会抛出任何异常,这就是为什么您不需要使用任何 try-catch 块。

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

好的。我试着解释得更深入一点。

你抱怨的是用户输入的权利吗? Beucase 你说,你想把int 作为输入。不是string 像“一月”或“五月”等。

当您使用Console.ReadLine() 方法读取输入时,它会返回string 作为返回类型,而不是int。不管用户输入3January,此方法都将它们作为string 返回,无论它们是什么类型。

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

【讨论】:

  • 对不起,我是新手,不知道如何阅读。 if(Int32.TryParse(s, out month)) { } 有什么作用?
  • @WindowsProdigy7 你没看我的回答吗?它说: 将指定样式和文化特定格式的数字的字符串表示形式转换为其等效的 32 位有符号整数。返回值指示转换是否成功。 它检查您的输入是否可以转换为Int32。如果您的对话成功,则返回true。如果你的对话不成功,它会返回false
  • 是的,这看起来像一个谷歌解决方案!无论如何,如果有用户交互,我会添加一个 try 和 catch 块 - 只是因为错误处理很重要!这真的节省了时间!
  • 这远远超出我的水平,我不知道这里发生了什么
  • 所以这需要字符串 s 并查看它是否可以变成一个没有异常的 int。它通过 Numberstyles.Integer 查看它是否想成为 int,CultureInfo.InvariantCulture 也不例外。那么 out month 是做什么的呢?
【解决方案2】:

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

原始代码将位于 try 块中,因为您想尝试运行它 - 但如果出现错误(例如用户键入 jan),catch 块会处理错误,您的程序可以继续运行而不会出现问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2017-07-21
    • 1970-01-01
    • 2019-10-17
    • 2021-06-25
    相关资源
    最近更新 更多