c# - 如何查看用户是否没有在 C# 中输入有效条目
问题描述
我想知道如果用户在下面的代码中输入了无效条目,如何输出。例如,如果他们输入了字符串字符或字符串字符和数字的组合。现在,如果输入了无效条目,它只会破坏程序。请保留最基本方法的答案,因为我对编程还很陌生!
Console.Write("Please enter the persons age: ");
int age = int.Parse(Console.ReadLine());
if(age == 17)
{
Console.WriteLine("That's to bad! You will have to wait until next year!");
}
else if (age < 18)
{
Console.WriteLine("That's to bad! You will have to wait a couple years until you can come in!");
}
else
{
Console.WriteLine("You are of age to be here.");
}
while (true)
{
Console.Write("Please enter the next persons age: ");
age = int.Parse(Console.ReadLine());
if (age == 17)
{
Console.WriteLine("That's to bad! You will have to wait until next year!");
}
else if (age < 18)
{
Console.WriteLine("That's to bad! You will have to wait a couple years until you can come in!");
}
else if (age > 18)
{
Console.WriteLine("You are of age to be here.");
}
else
{
Console.WriteLine("Please enter a valid entry");
}
}
解决方案
你可以做:
int age;
if (int.TryParse(Console.ReadLine(), out age))
{
if (age > 17)
{
Console.WriteLine("That's too bad! You will have to wait until next year!");
}
// etc
}
else
{
Console.WriteLine("Please enter a valid input");
}
说明:
int.TryParse
是一个接受 anstring
并尝试将其转换为 an 的方法int
,如果转换成功,它将结果分配给age
变量并返回 true 导致程序进入if
块,否则返回false
并且程序进入else
块。该age
变量是通过使用 C# 的输出参数功能分配的,这是一种将变量从外部传递给方法的方法,而后者承诺它将为其分配一些值。
推荐阅读
- excel - VBA宏根据日期将单元格值从工作表1复制/粘贴到2
- spring-webflux - 当有任何新数据时,Spring Webflux 发送事件
- python - 如何从文本文件中获取数据,然后在 Python 文件中使用提取的数据?
- laravel - 为什么在创建的观察者之前触发更新的观察者?
- angular - 使用 chrome 无头浏览器从 html 生成 pdf
- arrays - 如何使用 MongoDB 数据库在 Discord.js 中创建列表?
- reactjs - ./node_modules/react-router-dom/react-router-dom.js 尝试导入错误:“导航”未从“反应路由器”导出
- latex - 谁能告诉我一些关于 doxygen.sty 的事情?
- asp.net-core - 如何检测asp.net core api用户是人?
- prometheus-operator - Prometheus 操作员中的服务监视器问题