c# - 防止用户提交超出范围的值
问题描述
我的 C# 程序中有这段代码(目前是为 25-30 岁的成年人设计的)
Console.Write("Please enter in your age in the range of 25 - 30 years old: ");
string age = Console.ReadLine();
当提示用户时,我希望他们只输入值 25、26、27、28、29 或 30
我不希望用户输入超出范围的数字。
有没有办法可以防止这种情况发生,这样当用户输入超出范围的值时,会显示一条消息,说明用户输入了不正确的数字?
解决方案
Andrei 的回答很好,但是我建议int.TryParse
改用,因为您的用户可能会输入愚蠢的值,否则会使您的程序崩溃(例如:使用非数字字符):
Console.Write("Please enter in your age in the range of 25 - 30 years old: ");
int age;
while (true)
{
string strAge = Console.ReadLine();
// checks input validity (integer and within [25-30] range)
if (int.TryParse(strAge, out age) && age >= 25 && age <= 30)
{
Console.WriteLine("Welcome");
// ... and we leave the loop
break;
}
else
{
Console.WriteLine("Wrong input, please try again");
// ... and we go back to ReadLine
}
}
奖励:上面的代码使用循环,因此您的用户可以继续输入值,直到他们最终满足条件
推荐阅读
- azure - SQL 中是否有 CREATE TYPE 的替代方案,因为 Azure SQL 数据仓库不支持 CREATE TYPE
- flutter - Flutter:显示来自 HTTP 响应的文本
- excel - 从条件格式中获取颜色
- azure - 能够检索数据之前的 Azure 表存储持续时间
- css - CSS - 将 flex 容器的子元素与屏幕中心对齐无法正常工作
- javascript - 如何获取特定列之后的列?
- android - MotionEvent ACTION UP 无法检测到长按
- sql - 我无法弄清楚 SQL 语句中的 v_out 和 v_in 是什么意思
- c# - List.Except 自定义类的属性除外
- jquery - 单击时在移动视图上滑动菜单