简单c#:如何检查字符串输入是一个有效的数字并且小于某个数字
本文关键字:数字 有效 一个 小于 输入 何检查 简单 字符串 检查 | 更新日期: 2023-09-27 18:09:55
我知道&&int。TryParse(birthMonth, out monthInt) == false)是我的问题所在,但我发布它是为了更好地解释我的问题。
我希望验证用户输入(字符串)是一个数字,小于或等于12 -一个有效的月份。
// Get user's month of birth
Console.Write("'nFascinating! What month? (1-12): ");
birthMonth = Console.ReadLine();
// Check to see if user input for month is a number
int monthInt;
while (int.Parse(birthMonth) >= 13 && int.TryParse(birthMonth, out monthInt) == false)
{
Console.WriteLine("Invalid input. Please enter a number less than, or equal to 12!");
birthMonth = Console.ReadLine();
}
您需要首先使用int.TryParse
进行解析,然后检查解析后的数字,如:
while (!int.TryParse(birthMonth, out monthInt) || monthInt >=13)
还必须检查monthInt
是否小于1
。
注意事项:
- 使用
int.TryParse
,因为它在失败的情况下不会抛出异常。 - 使用
||
,因为它将根据您的条件进行短路评估和正确操作。
输入应该
- 表示
int
,即int.TryParse
应该返回true
- 至少为
1
- 最多为
12
While
下列条件失败 (!
-反转),loop:
while (!(int.TryParse(birthMonth, out monthInt) && monthInt >= 1 && monthInt <= 12)) {
...
}
调用Parse
和TryParse
,解析值两次,当一次就足够了:
int parsedMonth;
if (int.TryParse(birthMonth, out parsedMonth))
{
if (parsedMonth < 13)
{
// do whatever you need with the value
}
else
{
// out of range
}
}
else
{
// not a number
}
TryParse
解析后返回true
或false
;如果输入无效,Parse
将抛出异常。
这不是最简洁的书写方式,但是你可以更容易地遵循逻辑。
或者您可以使用TryParse和条件一起检查,如下所示。
int outvar = -1;
while (!int.TryParse(Console.ReadLine(),out outvar) && (outvar<=0 && outvar>12))
{
//your rest of the code
}
您需要使用TryParse
尝试将字符串值解析为原语。所有的原语——bool
、int
、byte
、DateTime
等等——都有这个方法。创建一个函数来验证输入:
var birthMonth = Console.ReadLine();
int month;
if(!ValidateMonth(birthMonth, out month) {
// process invalid month or whatever
}
bool ValidateBirthMonth(string birthMonth, out int month) {
var month = default(int);
if(!int.TryParse(birthMonth, out month)) {
Console.WriteLine("invalid month");
return;
}
if (month >= 1 && month <= 12) {
Console.WriteLine("... great!!!");
return;
}
Console.WriteLine("invalid entry: month must be 1-12");
}