C# 处理无效的用户输入
有一个简单的控制台应用程序,要求用户输入多个值。通过 console.readline() 读取输入。例如,
Name: Fred //string
Lastname: Ashcloud //string
Age: 28 //int
我想确保输入 int 和 double 类型,如果用户输入垃圾,让他重复该过程。
例如,如果用户输入“28 岁”(年龄预期为 int),则应用程序将崩溃。检查这些输入的最佳方法是什么?
现在我只能想到:
while (!Int32.TryParse(text, out number))
{
Console.WriteLine("Error write only numbers");
text = Console.ReadLine();
}
还有其他办法吗?如果想向用户提供更详细的反馈,请尝试 catch 语句?这种情况下怎么办?
Have a simple console app where user is asked for several values to input. Input is read via console.readline(). Ex
Name: Fred //string
Lastname: Ashcloud //string
Age: 28 //int
I would like to make sure that int and double types are entered and if the user enters garbage, lets him repeat the procedure.
Example, if the user enters "28 years old" where age expects int the app will crash. What is the best way to check for these inputs?
Right now I can only think of:
while (!Int32.TryParse(text, out number))
{
Console.WriteLine("Error write only numbers");
text = Console.ReadLine();
}
Is there any other way to do this? try catch statements if one wants to give a more detailed feedback to the user? How in that case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于控制台应用程序,您的代码非常好。
但是,您可能希望将其抽象为可重用的函数,以便您可以读取不同的数字而无需重复代码。
另外,您可能希望为用户提供某种取消方式。
For a console application, your code is perfectly fine.
However, you might want to abstract that into a reusable function so that you can read different numbers without repeating the code.
Also, you might want to provide some way for the user to cancel.
这将解析除年龄之外的所有数据,如果不存在年龄,则返回 -1。
这也假设年龄为 0-99 岁。
This will parse any data out besides the age or return -1 if no age is present.
this also assumes age 0-99.
事实上,你的代码很好。我会添加负数检查,也许还会添加巨数检查。
Actually, your code is good. I would add negative number check, and perhaps huge number check too.
正则表达式很好。
Regular Expressions are good.