C#停止用户输入字符/字符串而不是整数
我要求用户为他们的年龄输入一个int,但是当他们输入一个字符串时程序崩溃了(很明显) 我如何允许他们输入一个字符/字符串,但让程序显示一条有趣的消息,然后退出 到目前为止,我得到的是:C#停止用户输入字符/字符串而不是整数,c#,C#,我要求用户为他们的年龄输入一个int,但是当他们输入一个字符串时程序崩溃了(很明显) 我如何允许他们输入一个字符/字符串,但让程序显示一条有趣的消息,然后退出 到目前为止,我得到的是: Console.WriteLine("Please can you enter your age"); int userage = Convert.ToInt32(Console.ReadLine()); if (userage < 16) {
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
{
}
Console.WriteLine(“请输入您的年龄”);
int userage=Convert.ToInt32(Console.ReadLine());
如果(用户年龄<16岁)
{
var underage=新未成年人();
未成年人;
}
否则如果(用户年龄>122)
{
WriteLine(“没有人到过这个年龄,所以你不可能这么老”);
Console.WriteLine(“请下次输入不同的年龄!”);
WriteLine(“除非你真的这么老了,否则不要工作!!”;
Console.WriteLine(“按任意键退出程序。\n”);
环境。退出(0);
}
否则,如果(用户年龄尝试:
尝试:
使用该代码中的何处添加int.TryParse?在读取用户输入后的开始处。将控制台.ReadLine
存储在字符串变量中,并将其用作int.TryParse
的参数int.TryParse
返回bool
。如果为真,则int变量将具有有效值,如果为假,则您知道w用户输入不是有效的整数。请在读取用户输入后,在代码的开头使用我将在其中添加int.TryParse?的位置。将控制台.ReadLine
存储在字符串变量中,并将其用作int.TryParse
的参数。int.TryParse
返回一个bool
。如果为真,则int变量将返回一个bool
如果为false,则您知道用户输入不是有效的整数。
Console.WriteLine("Please can you enter your age");
int userage;
if (int.TryParse(Console.ReadLine(), out userage))
{
//your if block
}
else
{
Console.WriteLine("Your input is funny and I am a funny message\n");
Environment.Exit(0);
}