0
我要求用户输入一个int年龄,但程序崩溃时,他们输入一个字符串(显然)。C#停止用户输入一个字符/字符串,而不是整数
我该如何去允许他们输入一个字符/字符串,但程序显示一个有趣的消息,然后退出?
这是我这么远:
Console.WriteLine("Please can you enter your age");
int userage = Convert.ToInt32(Console.ReadLine());
if (userage < 16)
{
var underage = new underage();
underage.text();
}
else if (userage>122)
{
Console.WriteLine("No one has ever reached this age and so you can't possibly be this old");
Console.WriteLine("Please enter a different age next time!");
Console.WriteLine("Unless you really are this old, in which case don't work!!");
Console.WriteLine("Press any key to exit the program.\n");
Environment.Exit(0);
}
else if(userage<122)
{
Console.WriteLine("Ah brilliant, you are old enough to use our services\n");
Console.WriteLine("We shall continue as first planned\n");
}
else
{
}
使用['int.TryParse'](https://msdn.microsoft.com/en-us /library/f02979c7(v=vs.110).aspx) –
在那段代码中,我会添加int.TryParse? –
开始阅读用户输入之后。将'Console.ReadLine'存储在一个字符串变量中,并将其用作'int.TryParse'的参数。 'Int.TryParse'返回一个'bool'。如果它是真的,则int变量将具有有效值,如果它为假,则知道用户输入不是有效整数。 –